我对 Angular8 (2) 还比较陌生。
如何将用户信息发送到另一个名为“设置”的组件并将其显示在页面上?如果发生变化,会自动更新。
非常感谢任何帮助。
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;
}
最佳答案
您可以使用BehaviorSubject。
创建一个服务,然后在你的服务中;例如:
ng g s 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);
}
在你的组件中
您将通过依赖项注入(inject)将服务注入(inject)组件中。
constructor(private userService: UserService){}
userInfo: UserInfoModel;
ngOnInit(){
this.userService.userInfo$.subcribe(userInfo=>{this.userInfo = userInfo};
}
关于javascript - Angular 8,如何发送您从订阅另一个组件的服务中的 http 调用收到的用户信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58278074/