如何从角度http.get.subscribe

时间:2016-10-02 18:53:52

标签: json angular ionic2

我使用Ionic 2 Calendar显示已从远程服务器订阅为 json 的课程时间。我试图从我的订阅中提取响应并将其放入数组中,但是当将数据输出到console.log时,我得到" undefined"。

代码如下:

export class Calendar {
    eventSource;
    viewTitle;

    constructor(private navController:NavController, private httpService:HttpService) {
        var classes = [];
        this.httpService.getCalendarConfig()
            .subscribe(res => classes => res);

        console.log(classes);
    }

注意,如果我将.subscribe更改为:

    .subscribe(res => console.log(res));

它在控制台中显示JSON。

编辑:httpService类如下所示:

@Injectable()
export class HttpService {

    endpointUrl:string = '<address>';

    constructor(private http: Http) {}

    getCalendarConfig() {
        return this.http.get(this.endpointUrl + 'calendar.json')
                        .map(this.extractData)
                        .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? '${error.status} - ${error.statusText}' : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}

1 个答案:

答案 0 :(得分:2)

因为您在调用服务时考虑classes值适用。但这不会影响异步调用的工作方式。他们ajax完成后会立即提供输出。

您将获得classes

订阅成功的this.httpService.getCalendarConfig()对象
var classes = [];
this.httpService.getCalendarConfig()
    .subscribe(res => {
      classes => res;
      console.log(classes);
    });