简体   繁体   English

角度6,请求httpClient(类型错误)

[英]Angular 6, request httpClient (type errors)

I have errors in my services. 我的服务有误。 I'm trying to grab a list of medias (which was created by NodeJS, and that launches a JSON with all media). 我正在尝试获取媒体列表(该列表由NodeJS创建,并启动所有媒体的JSON)。 I can recover it but I have a "Property 'medias' error does not exist on the type 'Media []'". 我可以恢复它,但是在类型'Media []'上不存在“属性'medias'错误”。

Here is my service 这是我的服务

getMedias(): Observable<Media[]> {
    return this.http
      .get<Media[]>('http://localhost:3000/api/media')
      .map(mediasFetched => mediasFetched.medias);    <strong><!> L'erreur est juste ici <!></strong>
  }

My component where I get the media: 我获取媒体的组件:

this.mediaService.getMedias().subscribe(mediasFetched => {
      this.medias = mediasFetched;
      this.isLoading = false;
    });

If I do not add ".medias" to "mediasFetched" I only get an object that contains my table. 如果不将“ .medias”添加到“ mediasFetched”,则只会得到一个包含表的对象。 I have to go through this property to get my table and that's where my mistake is. 我必须经过此属性才能获取表,这就是我的错误所在。

I have to go through this property to browse it with a ngFor in my html. 我必须通过此属性才能在html中使用ngFor浏览它。

Excuse me in advance if I miss a big thing, but I start with Angular: p 如果我错过了一件大事,请提前打扰一下,但是我从Angular开始:p

Thank you 谢谢

In your model, try adding this medias: any[] 在您的模型中,尝试添加以下媒体:any []

export interface Media { 
   medias: any[]
}

I solved my problem, with <{medias: Media[]}>, remove the observable and add subscribe on my service. 我用<{medias:Media []}>解决了我的问题,删除了可观察对象并添加了对我的服务的订阅。

Service: 服务:

getMedias() {

    this.http
      .get<{ medias: Media[] }>(`${this.apiUrl}media`)
      .subscribe(mediasData => {
        this.medias = mediasData.medias;
        this.mediasUpdated.next([...this.medias]);
      });
  }

component.ts: component.ts:

this.mediaService.getMedias(); this.mediaService.getMedias();

@yer Thank you for your alternative @yer谢谢您的选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM