【发布时间】: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