我有一个服务,组件和模块。
服务中,我要发送 flag $ 变量的更改。
export class ListUserService {
public flag$ = new Subject< boolean >();
}
此组件对变量进行更改
export class ListUserComponent implements OnInit {
private flagPerfil = false;
getFlag() {
return this.flagPerfil;
}
constructor(private listUserService: ListUserService) {
}
functionThatGetsCalledWhenTheFlagIsChanged(){
this.listUserService.flags$.next(this.flagPerfil);
}
}
我需要在此模块中接收变量 flag $ :
export class Tab1PageModule {
public flagPerfil: boolean;
constructor(private listUserService: ListUserService) {
listUserService.flag$.subscribe((flag)=>{
console.log('FLAG', flag); //never show the console
this.flagPerfil = flag;
});
}
}
从不进入此控制台console.log('FLAG', flag);
,但是会发生此错误 TS2322:类型'Subject'不能分配给类型'boolean',并且在模块视图中什么也没有显示>
<ion-card-title> {{flagPerfil}} Puedes agregarlos para iniciar una amistad</ion-card-title>
答案 0 :(得分:1)
使用行为主体,因为它们具有默认值,并且任何新的观察者都会获得发出的最后一个值,主体仅在发出事件时通知观察者,最后的值会丢失给新的观察者。
export class ListUserService {
public flag$ = new BehaviorSubject<boolean>(false);
}
const { Subject, BehaviorSubject } = rxjs;
const subject$ = new Subject();
subject$.next('Subject initial val');
const behaviorSubject$ = new BehaviorSubject('BehaviorSubject initial val');
subject$.subscribe(val => { console.log(val); });
behaviorSubject$.subscribe(val => { console.log(val); });
subject$.next('Subject new val');
behaviorSubject$.next('BehaviorSubject new val');
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
并在组件中使用异步管道,因此您无需订阅代码。
export class ListUserComponent implements OnInit {
flags$ = this.listUserService.flags$;
constructor(private listUserService: ListUserService) {
}
functionThatGetsCalledWhenTheFlagIsChanged(value: boolean){
this.listUserService.flags$.next(value);
}
}
以及在视图模板中
<ion-card-title> {{flag$ | async}} Puedes agregarlos para iniciar una amistad</ion-card-title>