【问题标题】:Angular rxjs Subject : subscribing to a subject after emitting valuesAngular rxjs主题:在发出值后订阅主题
【发布时间】:2021-12-07 20:51:59
【问题描述】:

我阅读了article,其中指出,如果您在事件已经发出时订阅主题,您将丢失发出的值。他的演示示例如下。

let subject: Subject<string> = new Subject();
subject.next('test');
 
subject.subscribe((event) => {
  console.log(event);
});

但是,我实现了类似的方法,其中第一个主题将发出值,然后订阅主题。价值就在那里。没有丢失。代码如下。 在代码中,我们将身份验证信息保存在主题中。我们在标题组件中使用它来显示注销按钮和链接。问题是为什么我的代码可以正常工作,即使文章说它不会?

import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Subject} from "rxjs";
import { User } from "./user.model";

@Injectable({providedIn : "root"})
export class AuthService{

    constructor(private httpClient:HttpClient){}
    
    user = new  Subject<User>();   //emit new user when login or logout or token expired

    login(email:string,password:string){
        return this.httpClient
       .post<SignUpResponse>('https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyBCK9B2RcL0D4Bn8YaFCxE9rBXejTLNYQY',
        {
            email:email,
            password:password,
            returnSecureToken:true
        })
       .pipe(tap( response => this.handleAuthentication(response.email,response.idToken,response.idToken,response.expiresIn)))
    }


    private handleAuthentication(email:string,userId:string,token:string,expiresIn:string){

         const expirationDate = new Date(new Date().getTime() + +expiresIn * 1000)
         const user = new User(email,userId,token,expirationDate);
         this.user.next(user);
    }
}

Header.component.ts

import { Component,Output, EventEmitter, OnInit, OnDestroy } from "@angular/core";
import { Subscription } from "rxjs";
import { AuthService } from "../auth/auth/auth.service";
import { DataStorageService } from "../shared/data-storage.service";

@Component({
    selector : 'app-header',
    templateUrl:'./header.component.html'
})

export class HeaderComponent implements OnInit,OnDestroy{

    collapsed = true;
    private subscription : Subscription;
    isAuthenticated : boolean = false;

    constructor(private dataStorageService:DataStorageService,
                private authService:AuthService){

    }

    ngOnInit(){
        this.subscription =  this.authService.user.subscribe( user => {
        this.isAuthenticated = !!user; 
        console.log("User Object"); console.log(user); 
        console.log("IsAuthenticated value");  console.log(!!user);
    })
   }

    ngOnDestroy(){
        this.subscription.unsubscribe();
    }
}

【问题讨论】:

  • A ReplaySubject 会将最后一个值发送给新订阅者
  • 从您发布的代码中不清楚结果应该是什么。标头相对较早地订阅了底层用户主题,因此如果在该订阅发生之前调用登录,您就可以了。
  • behavioursubject 将发出最后一个值。 ReplaySubject 将允许缓冲区分配的值。但我的问题不是这样。我在这里使用一个普通的主题。在那个第一个我发出的值。然后订阅。根据文章价值应该丢失。但我的价值在那里.. 没有丢失
  • @EvanTrimboli 比较早的意思是? .你需要哪部分代码..我可以更新。

标签: javascript angular rxjs observable subject


【解决方案1】:

您的示例订阅正在运行的唯一原因是因为您在启动登录过程/方法之前加载了 Header 组件。组件的ngOnInit 在服务中的login 方法之前调用。

您的代码运行方式不是您在问题中描述的方式:

user = new  Subject<User>();
subject.next('test');

// then this runs in component ngOnInit 
this.authService.user.subscribe((event) => {
  console.log(event);
});

// when you try to login from inside the component then it runs the login method with next.
login(email:string,password:string){.....
this.user.next(user);  // now this is triggered hence you don't loose the user response.

【讨论】:

  • 该代码被执行。那个问题。
  • 我已经用图片更新了问题
  • "在您的示例订阅中运行的唯一方法是,如果您在启动登录过程/方法之前加载 Header 组件。"答案中的这一行有帮助吗?
  • 页眉组件在页面加载时被初始化。在标题组件中有一个登录链接。之后只有登录方法被调用。你能解释一下吗
  • 我已经更新了你现在关注的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 2021-12-30
  • 2020-12-13
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多