Angular 2 RXJ订阅可观察代码未执行



我有一个使用 rxjs 订阅从主题实例化的可观察量的角度应用程序。

下面是我的应用程序.服务.ts

private subjectGreeting: Subject<Greeting>;  //Subject declared
resGreeting: Observable<Greeting>;  //Observable declared
authenticate(credentials, callback) {
const headers = new HttpHeaders({ Authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
});
return this.http.get<Greeting>('http://localhost:8080/user', {headers},).subscribe(response => {
console.log('Inside app service authenticate');
if (response) {
this.subjectGreeting = new Subject(); //subjectGreeting being instantiated
this.resGreeting = this.subjectGreeting.asObservable();  //resGreeting being assigned asObservable()
this.subjectGreeting.next(response);   //next response being assigned to subjectGreeting
} 
callback();
});

在组件端,我有一个登录组件,它从上面的服务调用身份验证函数:

以下是组件代码:

login() {
console.log('inside login');
this.app.authenticate(this.credentials, () => {
this.app.authenticated = true;
this.childComponent.refreshFromParent();  //refresh child component (do a subscription after authentication)
// Redirect the user
this.router.navigate(['../home']);
} );

return false;
}

login() 函数还调用 refreshFromParent(),如下所示:

refreshFromParent(): void{
console.log('home component refresh from parent'); 
if(this.app.resGreeting){
this.subscriptionGreeting = this.app.resGreeting.subscribe(r => { ***//This subscription code is not executing despite the fact that it is being called after authentication***
console.log('inside greeting subscription');
if(r){
this.greeting = r;
this.authenticated = true;
}
});
}
}

最后,组件的 HTML 如下所示:

<a routerLink="./" routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }">Welcome Home!</a>
<div [hidden]="(authenticated)">
<p *ngIf="greeting">The ID is {{greeting.id}}</p>
<p *ngIf="greeting">The content is {{greeting.content}}</p>
</div>
<div [hidden]="!(authenticated)">
<p>Login to see your greeting</p>
</div>
<router-outlet></router-outlet>

由于某种原因,我没有得到任何输出{{greeting.id}}和{{greeding.content}}

使用BehaviorSubject而不是Subject

private subjectGreeting: BehaviorSubject<Greeting> = new BehaviorSubject<Greeting>(null);
resGreeting: Observable<Greeting> = this.subjectGreeting.asObservable();

Subject的订阅将在订阅后收到下一个值。 因此,如果您在调用this.subjectGreeting.next(..)后订阅了Subject,则订阅不会运行到next因为您订阅后再次调用

。通过切换到BehaviorSubject,您在订阅时始终会获得最新版本。

https://devsuhas.com/2019/12/09/difference-between-subject-and-behaviour-subject-in-rxjs/

最新更新