Angular - 在控制台中获取 json 值但不在视图中

Angular - getting json value in console but not in view

movie/id/external_ids?api_key=myapikey

{"id":335984,"imdb_id":"tt1856101","facebook_id":"BladeRunner2049","instagram_id":"bladerunnermovie", "twitter_id":"bladerunner"}

想要显示所有社交 ID 的值,例如 facebook、insta 和 twitter。不确定我在做什么错

组件:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { MoviesService } from '../movies.service';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.css']
})
export class MovieComponent implements OnInit {
  movie: Object;
  external_ids: Array<Object>;
  constructor(
    private _moviesServices: MoviesService,
    private router: ActivatedRoute      ) {

  }

  ngOnInit() {
    this.router.params.subscribe((params) => {
      const id = params['id'];
      this._moviesServices.getMovie(id).subscribe(movie => {
        this.movie = movie;
      });
      this._moviesServices.getExternalIds(id).subscribe((res: any) => {
        console.log(res.facebook_id);
        this.external_ids = res.external_ids;
      });
    })

  }
}

HTML

<p  *ngFor="let social of external_ids" class="text-primary" >
        <span *ngIf="social.facebook_id.length > 0" class="mr-3">
      {{social.facebook_id}}
      </span>
    </p>

您试图对一个对象使用 ngForngFor 只能遍历数组。使用 external_ids.facebook_id 直接在 UI 中显示它们似乎更容易,但如果您真的想使用 ngFor 通过遍历对象来显示所有这些,您可以使用 Object.keys 获取 ngFor

的数组

首先从您的组件公开 Object.keys

objectKeys = Object.keys;

然后在您的 HTML

中使用它
<p *ngFor="let social of objectKeys(external_ids)" class="text-primary">
    {{external_ids[social]}}
</p>

假设您想显示所有社交 ID,我已经删除了 ngIf

如果您想从对象中删除 id(因为它看起来像用户 ID 而不是社交 ID)

this._moviesServices.getExternalIds(id).subscribe((res: any) => {
    const {id, ...external_ids} = res;
    this.external_ids = external_ids;
});

编辑:虽然上述方法可行,但您也可以使用KeyValuePipe,将您的对象转换为数组,以便对其进行迭代。这样你就不需要使用 Object.keys

<p *ngFor="let social of external_ids | keyvalue" class="text-primary">
    {{social.value}}
</p>

Note: The keyValue method will work on Angular version 6+

这是 StackBlitz 上的一个工作示例。

您必须将 external_ids 转换为 ID 数组。这很容易,使用 Object.keys(external_ids)keys(external_ids) 使用 lodash's keys 函数。

并且不要忘记取消订阅。为此,请使用下面列出的任何选项:

  1. ngOnInit 中订阅并在 ngOnDestroy 中调用 unsubscribe 像这样:
subscription: Subscription;

ngOnInit() {
    this.subscription = someObservable.subscribe(...);
}

ngOnDestory() {
   this.subscription.unsubscribe();
}

  1. ngOnInit 中使用来自 rxjs/operators 的管道 takeUntil 像这样:
unsubscribe$ = new Subject<any>();

ngOnInit() {
  someObservable.pipe(
    takeUntil(this.unsubscribe$),
  ).subscribe(...);
}

ngOnDestory() {
   this.unsubscribe$.next(null);
   this.unsubscribe$.complete();
}

  1. 像这样使用 async 管道(在这种情况下您不需要取消订阅):

ts:

data$: Observable<object>;

ngOnInit() {
  this.data$ = someObservable;
}

html: {{ data$ | async | json }}

我更喜欢并推荐第二个,因为您可以为所有订阅使用一个主题并立即终止它。祝你好运!

如果您成功打印了这一行的 facebook id

console.log(res.facebook_id);

您没有将 facebook_id 值传递给您 external_ids 在此行

this.external_ids = res.external_ids;

那是因为 facebook_id 不是 external_id 的属性,而是 res.

的属性

所以我相信你解决这个问题的方法是这样的:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { MoviesService } from '../movies.service';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.css']
})
export class MovieComponent implements OnInit {
  movie: Object;
  external_ids: Array<Object>;
  constructor(
    private _moviesServices: MoviesService,
    private router: ActivatedRoute      ) {

  }

  ngOnInit() {
    this.router.params.subscribe((params) => {
      const id = params['id'];
      this._moviesServices.getMovie(id).subscribe(movie => {
        this.movie = movie;
      });
      this._moviesServices.getExternalIds(id).subscribe((res: any) => {
        console.log(res.facebook_id);
        this.external_ids = res;
      });
    })
  }
}

我只更改了您将响应传递给 external_ids 的行。 而且您不需要更改 HTML