【发布时间】:2020-04-30 03:24:39
【问题描述】:
我有一个带有 CORDOVA 的 IONIC APP。我只想从 URL GET a JSON。
我创建了一个服务调用 rest.service.ts
rest.service.ts
import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
@Injectable({
providedIn: 'root'
})
export class RestService {
BASE_URL = 'http://whatever.....';
constructor(public http: HTTP) {}
getProjects() {
const URL = this.BASE_URL + 'getProjects';
this.http.get(URL, {}, { 'Content-Type': 'application/json' })
.then(answer => {
return JSON.parse(answer.data);
})
.catch(error => {
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
}
}
在这个文件中,我可以看到信息。如果我插入类似...
console.log(JSON.parse(answer.data));
我可以在 JSON 中随心所欲地查看结果。
问题是当我尝试在其他文件中使用此方法时...
otherpage.page.ts
import { Platform } from '@ionic/angular';
import { RestService } from './../rest.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-otherpage',
templateUrl: './otheropage .page.html',
styleUrls: ['./otherpage .page.scss']
})
export class OtherPage implements OnInit {
projects;
constructor(
public platform: Platform,
public rest: RestService,
) {
this.projects = this.rest.getProjects();
console.log(this.projects); // UNDEFINED
}
ngOnInit() { }
}
这里...this.projects... 未定义... ¿发生了什么?我试过platform.ready,插入ngOnInit.. . 没有任何效果。
【问题讨论】:
标签: json angular api ionic-framework