代码之家  ›  专栏  ›  技术社区  ›  happyZZR1400

为什么使用异步过滤器会导致无尽的请求?

  •  0
  • happyZZR1400  · 技术社区  · 7 年前

     @Injectable({
        providedIn: 'root'
     })
     export class PostService {
       constructor(private http: HttpClient) { }
       getPosts(): Observable<Array<any>> {
          return this.http.get<Array<any>>(`http://localhost:9000/posts`);
       }
     }
    

    根据Angular docs,我可以通过两种方式使用“*ngFor”在我的组件中显示此集合:
    或:

    @Component({
      selector: 'app-root',
      template: '<div *ngFor="let post of posts">{{post.title}}</div>'
    })
    export class AppComponent {
      posts: any[];
      constructor(public postService: PostService) {}
      ngOnInit() {
        this.postService.getPosts().subscribe(_posts => this.posts= _posts);
      }
    }
    

    @Component({
      selector: 'app-root',
      template: '<div *ngFor="let post of posts$ | async">{{post.title}}</div>'
    })
    export class AppComponent {
      posts$: Observable<Array<any>>;
      constructor(public postService: PostService) {}
      ngOnInit() {
        this.posts$ = this.postService.getPosts()
      }
    }
    

    我的问题是:为什么这样写是错误的?(很明显,所有“ngOnInit东西”都可以幸免):

    @Component({
      selector: 'app-root',
      template: '<div *ngFor="let post of postService.getPosts() | async">{{post.title}}</div>'
    })
    export class AppComponent {
      posts$: Observable<Array<any>>;
      constructor(public postService: PostService) {}
    }
    

    我可以看出这是发送无尽的请求到服务器,但为什么?

    谢谢

    0 回复  |  直到 7 年前
    推荐文章