Angular 2 - 在视图中操作rxjs Observable

时间:2017-09-27 18:54:32

标签: javascript angular typescript rxjs

我开始使用Angular 2中的Observable,我无法弄清楚如何在我的视图中正确使用它们。

我使用Angular 2和angular-redux,并使用@select()装饰器从redux存储中检索selectedMovie$。这部分工作正常,组件基本上派遣一个redux事件来设置init的默认selectedMovie$。 redux商店已正确更新,但当我尝试在视图中完善它时,我遇到了一些问题。

import { Component, OnInit } from '@angular/core';
import { NgRedux, select } from '@angular-redux/store';
import { MovieActions} from '../store/app.actions';
import { IAppState} from '../store/reducers';
import { MovieService } from '../movie.service';
import { Observable } from 'rxjs/Observable';
import { IMovie } from '../movie.model';

@Component({
  selector: 'app-movies-container',
  templateUrl: './movies-container.component.html',
  styleUrls: ['./movies-container.component.css'],
  providers: [MovieService]
})
export class MoviesContainerComponent implements OnInit {
  movies: Array<IMovie>;
  @select() readonly selectedMovie$: Observable<IMovie>; // HERE - Get data from the redux store

  constructor(
    private movieService: MovieService,
    private movieActions: MovieActions,
    private ngRedux: NgRedux<IAppState>
  ) { }

  ngOnInit() {
    // Fetch movies and use the first one as default displayed movie.
    this.getMovies() // HERE - Takes the first movie and make it the default selectedMovie by dispatching a redux action
      .then(movies =>
        this.ngRedux.dispatch(this.movieActions.changeSelectedMovie(this.movies[0]))
      );
  }

  getMovies() { // HERE: Call an API, returns an array of movies in data.results
    return this.movieService.getMostPopular()
      .then(data => this.movies = data.results);
  }

  onSelect(movie: IMovie) {
    this.ngRedux.dispatch(this.movieActions.changeSelectedMovie(movie));
  }
}

以下是观点:

<div *ngIf="movies">
  <md-list>
    <h3 md-subheader>Most popular movies NOW!</h3>
    <pre>
      {{(selectedMovie$ | async | json).id}} // This fails and displays nothing. I'd expect it to display the movie id
    </pre>
    <md-list-item
      *ngFor="let movie of movies"
      [class.selected]="movie.id === (selectedMovie$ | async | json).id" // This is a real deal, I don't know what's the syntax to use. I wanted to compare ids
      (click)="onSelect(movie)"
    >
      <img src="https://image.tmdb.org/t/p/w92{{movie.poster_path}}" />
      {{movie.title}}
    </md-list-item>
  </md-list>

  <app-movie-card [movie]="selectedMovie$ | async | json"></app-movie-card> // This component gets the object correctly formatted
</div>

也许我只是没有使用正确的语法。或者我可能不应该首先在视图中使用观察者?

编辑:解决方案

<div *ngIf="movies && (selectedMovie$ | async); let selectedMovie">
  <md-list>
    <h3 md-subheader>Most popular movies NOW!</h3>
    <md-list-item
      *ngFor="let movie of movies"
      [class.selected]="movie.id === selectedMovie.id"
      (click)="onSelect(movie)"
    >
      <img src="https://image.tmdb.org/t/p/w92{{movie.poster_path}}" />
      {{movie.title}}
    </md-list-item>
  </md-list>

  <app-movie-card [movie]="selectedMovie"></app-movie-card>
</div>

1 个答案:

答案 0 :(得分:3)

问题源于一个常见的误解,即JSON是普通对象的同义词。 不是

json管道将输入转换为实际的 JSON字符串。所以(selectedMovie$ | async | json)表达式求值为一个字符串,并且没有id属性。

使用AoT编译很有帮助,因为它允许检测模板中的类型问题,并且在这种情况下可能会导致类型错误。

应该是(selectedMovie$ | async).id

如果多次使用(selectedMovie$ | async)(如本例所示),则会产生多个订阅。可以通过将其分配给局部变量来优化它,如here所述:

<div *ngIf="movies">
  <ng-container *ngIf="(selectedMovie$ | async); let selectedMovie">
    ...
    {{selectedMovie.id}}
    ...
  </ng-container>
</div>