在HTML中显示Observable <any [] =“”>返回类型

时间:2016-12-29 03:03:49

标签: angular

Angular 2新手,所以可能有点基础。

我有一个服务函数getMedia,它是一个Observable类型,任何[]在订阅时将此信息返回给组件:

 getMedia return data

基本上,这是一个对象数组,所以在我的组件中我写了这个:

export class RecommendationFeedComponent implements OnInit {

  result:Array<Object>=[];

  constructor(private feedService: FeedService, private authService: AuthService,
              private auth: FirebaseAuth, public af: AngularFire) { }

  ngOnInit() {
    this.af.auth.subscribe(
        (user) => {
            if (user) {
              this.feedService.getMedia(user.auth.email)
                  .subscribe(result => this.result = result);
              console.log(this.result);
            }
    })

  }

控制台返回空,所以我不知道如何使用它来显示HTML上的数据。

更改了组件和模板:

import { Component, OnInit } from '@angular/core';
import {FeedService} from "../shared/model/feed.service";
import {RestaurantMedia} from "../shared/model/restaurantMedia";
import {Observable} from "rxjs/Rx";
import {ActivatedRoute, Router} from "@angular/router";
import {AuthService} from "../shared/security/auth.service";
import {FirebaseAuth, AngularFire} from "angularfire2/index";


@Component({
  selector: 'recommendation-feed',
  templateUrl: './recommendation-feed.component.html',
  styleUrls: ['./recommendation-feed.component.css']
})
export class RecommendationFeedComponent implements OnInit {
  //Medias = [];
  //RestaurantMedias$: Observable<any[]>;
  result:Array<Object>=[];


  constructor(private feedService: FeedService, private authService: AuthService,
              private auth: FirebaseAuth, public af: AngularFire) { }

  ngOnInit() {

        this.af
        .auth
        .flatMap(user => this.feedService.getMedia(user.auth.email))
        .subscribe(result => {
               this.result = result;
            //  console.log(this.result);
            })



  }

}

//此

下方的HTML模板代码
<tr class *ngFor="let media of (result)">
   <td>
     <img src={{media.data.images.standard_resolution.url}} height="100" width="100">
  </td>
</tr>

1 个答案:

答案 0 :(得分:4)

subscribe是异步的,因此你的console.log应该在其中,否则即使在调用subscribe函数之前它也会被调用。

所以要解决它:

更改:

         this.feedService.getMedia(user.auth.email)
              .subscribe(result => this.result = result);
          console.log(this.result);

    this.feedService.getMedia(user.auth.email)
              .subscribe(result => {
                      this.result = result
                     console.log(this.result);

               });

顺便说一下,这是一个更好的方式:

ngOnInit() {
    this.af
        .auth
        .flatMap(user => this.feedService.getMedia(user.auth.email))
        .subscribe(result => {
               this.result = result);
              console.log(this.result
         });

如果您只想在html中显示结果而不对其执行任何操作,则可以使用异步管道:

  ngOnInit() {
    this.result = 
      this.af
        .auth
        .flatMap(user => this.feedService.getMedia(user.auth.email)) // no subscribe 

然后在你的模板中:

<div >
       {{result | async | json }}
    </div>