我认为这就是您的组件的结构方式:
// In app.component.html
<app-navbar></app-navbar>
<router-outlet></router-outlet> // For rest of the pages.
在这里,我们可以通过两种方式(我不会谈论包括 ngModel)将数据传递给导航栏以更新导航栏的状态/数据。
1.使用输入/输出装饰器。
// Your navbar.component.ts
// I'm assuming you have set up model for User. If no, then change the type to **any**.
@Input() currentUser: IUser;
// Your navbar.component.html
<p *ngIf="currentUser"> {{currentUser | json}} </p> // Render this if currentUser exists. By default, it is undefined.
现在,在您的应用组件中:
//In your app.component.ts
User: any | IUser;
public authenticateUser() {
this.someServiceToAuthenticateUser.subscribe(
res => this.User = res,
error => console.error(error)
);
}
// In your app.component.html
<app-navbar [currentUser]="User"></app-navbar>
<router-outlet></router-outlet>
-
使用公共服务。
您可以创建将经过身份验证的用户存储在其中的公共服务。在您的App 组件中,您可以将用户设置为成功验证响应,并且从其他组件中,您可以获取经过验证的用户。
export class UserService {
private currentUser: IUser | any;
setCurrentUser(userToSet: any) {
this.currentUser = userToSet;
}
getCurrentUser() {
return this.currentUser;
}
现在,在你的App组件中,如果认证使用请求成功,则设置UserService的currentUser:
//In your app.component.ts
User: any | IUser;
public authenticateUser() {
this.someServiceToAuthenticateUser.subscribe(
res => this.UserService.setCurrentUser(res),
error => console.error(error)
);
}
现在,在您的导航栏组件中,从 UserService 获取当前用户。
// In navbar.component.ts
currentUser: any;
constructor(private userServicce: UserService) {
getuserFromservice();
}
public getuserFromservice() {
setInterval(() => {
curretnUser = this.userService.getCurrentUser()
}, 3000);
重要提示:在这种方法中,请注意在导航栏组件中,我在 setInterval 中设置了当前用户。这是因为您的 getuserFromservice() 只会运行一次(当它第一次创建/渲染时),此时 userService 将没有 currentUser。所以导航栏永远不会得到当前用户。
如果您想替换 setInterval 方法(我强烈建议替换它),请使用 Subjects/BehaviourSubject/ReplaySubject。我没有在这里包含它们,因为 Rxjs 本身就是一个巨大的话题,在这里包含它会太难理解。