簡體   English   中英

Angular 8,如何發送從 http 調用中收到的用戶信息,並訂閱另一個組件?

[英]Angular 8, How can I send the userinformation I recieve from a http call in a service with subscribe to another component?

我對 Angular8 (2) 比較陌生。

如何將userInformation發送到另一個名為 settings 的組件並將其顯示在頁面上? 如果有什么變化會自動更新。

任何幫助都非常感謝。

export interface UserInfoModel {

id: string;
email?: string;
firstName?: string;
lastName?: string;
mobile?: string;
createdAt: string;

}

private userInformation: UserInfoModel;

this.http
  .post<RequestResponse>(`${API_BASE_URL}user/login`, loginData)
  .pipe(catchError(this.errorHandler))
  .subscribe(response => {
    const token = response.content.token;
    const userId = response.content.id;
    const email = response.content.email;

    // added to UserInfo
    this.userInformation = {
      id: response.content.id,
      email: response.content.email,
      firstName: response.content.firstName,
      lastName: response.content.lastName,
      mobile: response.content.lastName,
      createdAt: response.content.createdAt
    };

    this.token = token; // add token to local var
    this.userId = userId;
}

我使用 http 請求創建了一個示例,以演示如何將響應發送到子組件。

https://stackblitz.com/edit/angular-wgghzt

基本上,子組件可以通過在子組件上使用Input() myVar來接受傳入的數據。

如果希望子組件將消息發送回父組件,可以使用Output() myVar2

這是一個很好的代碼示例,演示了孩子和父母的溝通是如何工作的。

https://stackblitz.com/edit/angular-input-example

您可以使用 BehaviorSubject。

創建一個服務,然后在你的服務中; 例如:

ng gs user其中 user 是您的服務的名稱。

import { BehaviorSubject } from 'rxjs';

private userInfo = new BehaviorSubject< UserInfoModel>(null);
userInfo$ = this.userInfo.asObservable();

 .post<RequestResponse>(`${API_BASE_URL}user/login`, loginData)
  .pipe(catchError(this.errorHandler))
  .subscribe(response => {
    //your existing code here
    this.setUserInfo(this.userInformation);


    this.token = token; // add token to local var
    this.userId = userId;
}


setUserInfo(userInfo: UserInfoModel): void {
  this.userInfo.next(userInfo);
}

在您的組件中

您將通過依賴注入將您的服務注入到組件中。

constructor(private userService: UserService){}
userInfo: UserInfoModel;
ngOnInit(){
  this.userService.userInfo$.subcribe(userInfo=>{this.userInfo = userInfo};
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM