【问题标题】:angular2 services returns undefinedangular2 服务返回未定义
【发布时间】:2017-03-23 04:34:26
【问题描述】:

我无法理解为什么我的一项服务总是返回 undefined 但是开发人员模式下的网络选项卡显示已收到数据。

有人可以帮我找出我的错误在哪里吗?

我的组件看起来下一个:

export interface Sponsors {
      id;
      sponsorCode;
      sponsorName;
      active;
      clientId;
      countryId;
      cloudRegionId;
    }

    @Component({
      selector: 'app-sponsors',
      templateUrl: './sponsors.component.html',
      styleUrls: ['./sponsors.component.css'],
    })

    export class SponsorsComponent implements OnInit {

      id: any;     
      sponsors: Sponsors[];
      applications: Applications[];

      constructor(private appService: AppServices,
                  private route: ActivatedRoute) {
        this.id = route.snapshot.url[1].path;
      }

      ngOnInit() {
        this.getSponsors();
        this.getApps();
      }

      getSponsors () {
        this.appService.getSponsorsByClient(this.id).then(
          response => {
            this.sponsors = response;
            console.log(this.sponsors) //returns undefined
        });
      }

      getApps(){
        this.appService.getApplications()
          .then(applications => {
            this.applications = applications;
            console.log(this.applications) // returns data
          });
      }

这是我的服务:

getSponsorsByClient(id: any): Promise<Sponsors[]> {
    const url = `${this.api}/clients/${id}/sponsors`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as Sponsors[])
  }

getApplications(): Promise<Applications[]> {
    return this.http
      .get(this.api + "/applications")
      .toPromise()
      .then(response => response.json() as Applications[])
  }

提前致谢

【问题讨论】:

  • .then(response =&gt; response.json().data as Sponsors[]) 这确实有.data,而另一种方法则没有。会是这个原因吗?
  • @YaroslavAdmin 太傻了,这是我的问题。感谢您的通知!

标签: angular angular2-services


【解决方案1】:

应该可以的:

getApplications(): Promise<Applications[]> {
    return this.http.get(this.api + "/applications")
               .map(response => response.json() as Applications[])
               .toPromise();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多