网站搜索

typescript - Angular 5 更新视图


我的 app.component 收到了日期,但在用户注销后再次登录,这个数据仍然相同。只有刷新页面后视图才显示正确的日期。

当数据库中的数据被更改时,如何在视图上更新日期?

app.component

ngOnInit() {
    this.getCurrentUser()
  }

getCurrentUser() {
      this.apiService.getCurrentUser().subscribe(
      data => { this.user = data },
      err => console.error(err)
    );   
}

app.component.html

<p>{{user.name}}</p>

api.服务

getCurrentUser() {
  return this.http.get<any>(this.path + '/curruser')
}

auth.service

loginUser(loginData) {
    this.http.post<loginUserData>(this.path + '/login', loginData).subscribe(res => {     
      this.saveToken(res.token)
      this.router.navigate(['/'])

    }, error => {
      console.log('error', error)
    })
  }

答案#1

问题是你没有在 ngOnInit 中为实际的数据更新设置初始订阅。你对接收数据的订阅确保了你的应用接收数据,但你的应用组件并不知道数据已经被异步更新。因此,你需要一个单独的订阅来更新你的数据/视图。

做类似这样的事情:

userSubcription: Subscription;

ngOnInit() {
    this.userSubscription = this.userService.dataReceived.subscribe(
    (user) => {
      this.user = user;
    });
    this.getCurrentUser();
}

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

getCurrentUser() {
      this.apiService.getCurrentUser().subscribe(
      data => this.userService.dataReceived.next(data),
      err => console.error(err)
    );   
}

你将需要一个额外的 userService 来创建一个你可以订阅的 Subject。

答案#2

你的代码没有问题,但是从后端服务请求当前用户只会发生一次,如果不重新请求,它是不会更新的。

如果 ApiService 正在存储当前用户,该用户应该是一个可以更新的可观察对象:

user: new BehaviorSubject<User>();

然后在 ApiService 中,如果用户登录或登出:

login() {
  // omitted code that obtains user data in response
  // ...
  this.user.next(response.data);
}

logout() {
  this.user.next(null);
}

最好使用 async 管道,让 Angular 为你处理订阅:

<p *ngIf="apiService.user | async as user">{{ user.name }}</p>

确保你将 apiService 注入为 public

constructor(public apiService: ApiService) {}