发生更改时数组未更新Angular 10 [英] Array not updated when changes occur Angular 10

查看:53
本文介绍了发生更改时数组未更新Angular 10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 Observable 可将要约数组发送到我的组件.但是,当列表更改时(一个被删除),它不会更改我在组件中得到的列表.

There is an Observable that sends an array of offers to my component. But when the list is changes (one is deleted) it does not change the list that I get in the component.

我已尝试使用 ngOnChanges 再次订阅该列表并更新组件中的列表,但是它没有检测到该列表上的任何更改.

I've tried it with ngOnChanges to subscribe to the list again and update the list in my component, but it doesn't detect any changes on the list.

当我使用 ngDoCheck 时,它可以工作,但是我想要的解决方案要少一些.

When I use ngDoCheck it worked, but I want a little less drastic solution for this..

offer.service.ts :

    // observable of offers list
      public getAll(): Observable<Offer[]> {
        return of(this.offers);
      }

component.ts:

    offers: Offer[] = [];
      selectedOfferId = -1;
    
      constructor(private offerService: OfferService) { }
    
      ngOnInit(): void {
        this.offerService.getAll().subscribe(data => {
          this.offers = data;
        });
      }
    
      ngOnChanges(): void {
        this.offerService.getAll().subscribe(data => {
          this.offers = data;
        });
      }

推荐答案

您可以使用Observable和Subject(这是一种可观察的对象)在组件之间进行通信,我不会在细节上做太多介绍,您可以在此处中查找更多信息,有两种方法:Observable.subscribe()和Subject.next().

You can communicate between components using an Observable and a Subject (which is a type of observable), I won't go too much into the details, you can fin more info here, there are two methods: Observable.subscribe() and Subject.next().

Observable.subscribe()

角度组件使用observable订阅方法来订阅发送到observable的消息.

The observable subscribe method is used by angular components to subscribe to messages that are sent to an observable.

Subject.next()

下一个主题方法用于将消息发送到可观察对象,然后将消息发送到该可观察对象的所有角度组件.

The subject next method is used to send messages to an observable which are then sent to all angular components that are subscribers of that observable.

一种解决方法:

offer.service.ts:

offer.service.ts:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class OfferService {
    private subject = new Subject<any>();
    
    //...

    getOffers(message: string) {
        return this.subject.asObservable();
    }

    removeOffers() {
      //...remove logic
      this.subject.next({this.offers})
    }

}

component.ts:

component.ts:

 subscription: Subscription;

 ngOnInit(): void {
       this.subscription =  this.offerService.getOffers().subscribe(offers => {
          //...
       })
 }

这篇关于发生更改时数组未更新Angular 10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆