angular2 服务返回未定义 [英] angular2 services returns undefined

查看:21
本文介绍了angular2 服务返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cannot get the reason why one of my services always returns undefined however network tab in developer mode shows me that data has been received.

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

Could somebody help me to figure out where my mistake is?

我的组件看起来像下一个样子:

My component looks next way:

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[])
  }

提前致谢

推荐答案

那应该可行:

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

这篇关于angular2 服务返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆