为什么我的组件没有使用 Observable 返回的数据进行更新?

问题描述 投票:0回答:1

这是我的组件的 .ts 文件:

 _myMovieRating: number = 0;

  get myMovieRating(): number {
    return Number(this._myMovieRating);
  }
  set myMovieRating(value: number) {
    this._myMovieRating = value;
    console.log('In setter:', this._myMovieRating);
  }


  ngOnInit(): void {
    const userId = Number(this.route.snapshot.paramMap.get('userId'));
    const movieId = this.route.snapshot.paramMap.get('movieId');
    if (movieId) {
      this.getMovie(userId, movieId);
      this.myMovieRating = this.getMovieRating(userId, movieId); 
      console.log('My Movie Rating: ' + this.myMovieRating);
    }
  }

getMovieRating(userId: number, movieId: string): number {
    this.userService
      .getUser(userId)
      .pipe(
        map((user) => {
          let found = user.movieRatings.find((rating) => rating.id == movieId);
          return user.movieRatings.find((rating) => rating.id == movieId)
            ? user.movieRatings.find((rating) => rating.id == movieId)?.rating
            : 0;
        })
      )
      .subscribe((returnedData) => console.log(returnedData));

    return 0; //is there a cleaner way to do this in the above call?
  }

这是模板:

<div class="container">
    <h1>{{movie?.name}}</h1>
    <h3>Link: <a [href]="movie?.link">Open IMDB Page</a></h3>
    <h3>Year Released: {{movie?.year}}</h3>
    <h3>Official Rating: {{movie?.rating}}</h3>   
    <span><h3>My Rating (0-5): </h3> 
        <pm-star [rating]="myMovieRating"></pm-star> 
        <input type="text" [(ngModel)] = "myMovieRating"/>
        <button type="button" class="btn btn-primary" (click)="saveRating()">Save</button>
    </span>
</div>

在浏览器的控制台中,我首先看到: 我的电影评分:0 然后,从 console.log(returnedData) 中,我看到 4.7 已记录在浏览器控制台中。所以我知道 getMovieRating() 函数正在返回数据,并且我知道它绑定到模板,但它没有反映在 UI 中,我不明白为什么它不自动更新。我是不是错过了什么?

angular templates components observable subscribe
1个回答
0
投票

尝试如下所示(模板中具有可观察值的异步管道):

<ng-container *ngIf="userId && movieID && (getMovie(userId, movieId) | async as movie)">
<div class="container">
    <h1>{{movie?.name}}</h1>
    <h3>Link: <a [href]="movie?.link">Open IMDB Page</a></h3>
    <h3>Year Released: {{movie?.year}}</h3>
    <ng-container *ngIf="getMovieRating() | async as rating">
    <h3>Official Rating: {{movie?.rating}}</h3>   
    <span><h3>My Rating (0-5): </h3> 
        <pm-star [rating]="myMovieRating"></pm-star> 
        <input type="text" [(ngModel)] = "myMovieRating"/>
        <button type="button" class="btn btn-primary" (click)="saveRating()">Save</button>
    </span>
    </ng-container>
</div>
</ng-container>
© www.soinside.com 2019 - 2024. All rights reserved.