【问题标题】:BehaviorSubject doesn't emit valuesBehaviorSubject 不发出值
【发布时间】:2021-08-11 17:30:11
【问题描述】:

在 switchMap 运算符从父组件到子组件之后,我在从行为主体发出值时遇到问题。如果我在子组件的console.log中调用真正的http API,我只会看到空数组[](默认值),但是如果我在console.log数据中看到包含20个项目的数组,但在子组件中没有.当我尝试制作模拟服务并返回模拟数据时。

例如。 return of(['item1', 'item2']

这种情况工作正常,但是当我只切换呼叫服务名称时,它对我来说不能正常工作,在点击中我看到数据,但在子输入中没有。

import { Component, VERSION } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { AppserviceService } from './appservice.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  refresh$: Subject<void> = new Subject();
  data$: BehaviorSubject<string[]> = new BehaviorSubject<string[]>([]);

  constructor(private _appService: AppserviceService) {
    this.refresh$
      .pipe(switchMap(() => this._appService.test2()))
      .subscribe(res => {
        console.log('Subscribe:');
        console.log(res);
        this.data$.next(res)
      });

    this.refresh$.next();
  }
}


子组件

import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'hello',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <h1>Hello {{ name }}!</h1>
  `,
  styles: [
    `
      h1 {
        font-family: Lato;
      }
    `
  ]
})
export class HelloComponent {
  @Input() name: string;
  @Input() set test(value: BehaviorSubject<any[]>) {
    console.log(value.getValue());
  }
}

https://stackblitz.com/edit/angular-ivy-7wezwh?file=src/app/app.component.ts

你遇到过这个问题吗?谢谢。

【问题讨论】:

  • 尝试此行之前的控制台日志数据this.childData$.next(data);
  • 尝试用refresh$ = new BehaviorSubject();替换refresh$ = new Subject();
  • 当我 console.log 数据时,我看到了结果。而且我认为,行为主题是不正确的,因为我不需要任何默认值。但是我用默认的空值尝试了它,也不起作用。 stackblitz 上有一个例子。在服务中,我有两个 API,一个是模拟的,第二个是真实的 API。模拟工作正常,但第二次不行。 stackblitz.com/edit/angular-ivy-7wezwh?file=src/app/…

标签: angular typescript rxjs rxjs-observables


【解决方案1】:

原因是您的子组件在您的 http 调用完成之前被实例化。现在你只是getValue()ing 第一个值。如果您希望 BehaviorSubject 每次有新数据时都发出新数据,您可以通过简单地添加异步运算符来解决此问题:

<hello name="{{ name }}" [test]="data$ | async"></hello>
@Input() set test(value: any[]) {
  console.log(value);
}

现在每次BehaviorSubject 有一个新值,它都会被发送到你的子组件

Fixed stackblitz

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2020-01-24
    相关资源
    最近更新 更多