angular2 services returns undefined

拟墨画扇 提交于 2019-12-12 03:48:36

问题


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
          });
      }

This is my services:

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

Thanks in advance


回答1:


That should work:

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


来源:https://stackoverflow.com/questions/42961973/angular2-services-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!