繁体   English   中英

angular 2 rxjs 订阅未执行的可观察代码

[英]angular 2 rxjs subscribe to observable code not executing

我有一个 angular 应用程序使用 rxjs 订阅从主题实例化的可观察对象。

下面是我的 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();
});

在组件方面,我有一个登录组件,它从上述服务调用验证 function:

以下是组件代码:

    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() function 也调用 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>

出于某种原因,我没有得到任何 output {{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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM