【问题标题】:Subject.next() not firing from inside observableSubject.next() 没有从可观察的内部触发
【发布时间】:2021-04-30 08:31:28
【问题描述】:

service.ts

constructor() {
    this.cartUpdate = new BehaviorSubject<Array<AppCartItem>>([]);
    // this.cartUpdate.subscribe((items) => {   // #### 1
    //   console.log('Service Items : ', items);
    // });
}
add(item) : Observable<Array<AppItem>> {
    return this.get().pipe(
      switchMap(cartItems => {
        let index = cartItems.findIndex(i => i.item.id == item.id);
        if(index == -1) {
          cartItems.push({ item });
        }
        return this.updateUser({ 'cart': cartItems })
        .pipe(
          map(() => {
            return cartItems;
          })
        )
      }),
      catchError(err => {
        console.log('Error : ', err);
        return throwError(null);
      })
    ).pipe(
      map(cartItems => {
        this.updateCart(cartItems);
        return cartItems;
      })
    )
}

updateCart(items) {
    setTimeout(() => {
      this.cartUpdate.next(items);  // #### 3
    }, 1000);
}

component.ts

ngOnInit() {
  this.service.cartUpdate.subscribe((items) => {  // ####4
    console.log('Items : ', items);
  }, (err) => {
    console.log('Error : ', err);
  });
}

我已经提供了服务和组件的代码。 最初,在组件中触发订阅。没有问题。 #### 4

现在,service.ts 中的 add 方法也应该在添加项目后触发 observable。 #### 3

但是订阅组件没有触发发射。 #### 3

而在构造函数中为同一主题订阅正在工作。 #### 1

我无法弄清楚为什么组件中的订阅不起作用

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

    有些方法需要改正, 当价值发生变化时,订阅总是会响应。 给你做个例子,跟着这个吧

    Service.ts

    import { Injectable } from '@angular/core';
    import { BehaviorSubject, of } from 'rxjs';
    
    @Injectable()
    export class ServiceService {
    cartUpdate = new BehaviorSubject([]);
    constructor() { }
    add() {
        this.cartUpdate.next([1,2,1])
        this.updateCart([2, 12]);
        return this.cartUpdate.asObservable();
    }
    updateCart(items) {
        setTimeout(() => {
            console.log('calling');
            this.cartUpdate.next(items);
            console.log(this.cartUpdate);
        }, 3000);
    }
    }
    

    component.ts

    ngOnInit(): void {
    this.service.add().subscribe(res =>{
      this.response = res;
      console.log('Hi'+ res);
    })
    }
    

    演示: StackBlitz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多