我有一個 angular 應用程式,它使用 rxjs 訂閱從主題實體化的 observable。
下面是我的 app.service.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}}
uj5u.com熱心網友回復:
使用 aBehaviorSubject代替 a Subject。
private subjectGreeting: BehaviorSubject<Greeting> = new BehaviorSubject<Greeting>(null);
resGreeting: Observable<Greeting> = this.subjectGreeting.asObservable();
對 a 的訂閱Subject將在訂閱后收到下一個值。因此,如果您訂閱Subjectafterthis.subjectGreeting.next(..)被呼叫,則訂閱不會next再次呼叫,因為您訂閱了之后。
通過切換到 a,BehaviorSubject您在訂閱時總是可以獲得最新的。
https://devsuhas.com/2019/12/09/difference-between-subject-and-behaviour-subject-in-rxjs/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/398028.html
