我写了这个简单的HTTP提供程序:
google-services.json
这里是使用它的组件:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class GetQueriesProvider {
constructor(public http: HttpClient) { console.log('Hello GetQueriesProvider'); }
getRemoteData() {
return new Promise(resolve => {
this.http.get('/TJSON/t22.json').subscribe(data => {resolve(data);}, err => {console.log(err);});
});
}
}
我无法解决的问题(我想这是一个微不足道的问题)是在“扇区1”上,this.sectors是“未定义”。
这是控制台日志:
import { Component } from '@angular/core';
import { Sector } from "../../models/sector.models";
import { GetQueriesProvider } from '../../providers';
@Component({ selector: 'app-sector', templateUrl: './sector.html'})
export class SectorComponent {
sectors: any;
constructor(public getDataService: GetQueriesProvider ) {
this.getData().then((data) => { this.sectors = data; console.log("1: ", this.sectors);});
console.log("2: ", this.sectors);
}
getData() { return this.getDataService.getRemoteData(); }
ngOnInit() { }
}
有人可以帮我吗?
谢谢!
答案 0 :(得分:0)
请将您的组件代码更改为以下内容
import { Component } from '@angular/core';
import { DOMANDETEST } from '../../assets/domandeTest';
import { DOMANDEDUMMY } from '../../assets/domandeDummy';
import { Sector } from "../../models/sector.models";
import { GetQueriesProvider } from '../../providers';
import { QuestionsProvider } from '../../providers';
@Component({
selector: 'app-sector',
templateUrl: './sector.html'
})
export class SectorComponent {
sectors: Sector[];
constructor(public getDataService: GetQueriesProvider, public questionsService: QuestionsProvider) {
this.sectors = DOMANDEDUMMY;
this.getData().then((data) => {
if (data.length < 2) {
this.sectors = DOMANDETEST;
} else {
this.sectors = data;
}
this.questionsService.set(this.sectors);
});
}
getData() {
// return this.getDataService.getRemoteData().then(data => {
// this.questionsService.set(data);
// console.log("Sectors 0: ", this.questionsService.sctrs);
// return data;
// });
return this.getDataService.getRemoteData();
}
ngOnInit() { }
}
答案 1 :(得分:0)
我怀疑这是同步问题...确实如此。此链接完全报告亩情况:https://www.joshmorony.com/dealing-with-asynchronous-code-in-ionic/
所以我想我现在要做的是使用@output()装饰器来同步我的页面