我正在检查离子2中是否解决了诺言。这是我的代码:
ionViewDidLoad() {
this.loader.present();
this.getCourses();//after resolve to do something
}
public getCourses(){
this.coursesData.LoadData()
.subscribe(courseList=> {
courseList.forEach(course=>{
var newCourse={
id_course:course.id_course ,
key_course:course.key_course,
course_name:course.course_name ,
course_type:course.course_type ,
start:course.start ,
end:course.end ,
point_course:course.point_course ,
day:course.Day,
class:course.class,
lecture_name:course.lecture_name
}
this.coursesA.push(newCourse);
console.log(this.coursesA);
});
this.loader.dismiss();
// return this.coursesA;
},err=>{
console.log(err);
});
}
我有this.getCourses()
函数,在解析后我想对数据执行其他操作。这是我的提供商course-data.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the CoursesData provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class CoursesData {
public data: any = null;
constructor(public http: Http) {
console.log('Hello CoursesData Provider');
}
LoadData(){
let link = "http://adirzoari.16mb.com/selectCourses.php";
return this.http.get(link)
.map(res => res.json());
}
}
答案 0 :(得分:0)
你可以做承诺链。
public getCourses(){
return new Promise(function(resolve, reject){
this.coursesData.LoadData()
.subscribe(courseList=> {
courseList.forEach(course=>{
var newCourse={
id_course:course.id_course ,
key_course:course.key_course,
course_name:course.course_name ,
course_type:course.course_type ,
start:course.start ,
end:course.end ,
point_course:course.point_course ,
day:course.Day,
class:course.class,
lecture_name:course.lecture_name
}
this.coursesA.push(newCourse);
console.log(this.coursesA);
});
this.loader.dismiss();
resolve();
},err=>{
console.log(err);
reject(err);
});
});
}
ionViewDidLoad() {
this.loader.present();
var getCoursesPromise = this.getCourses();
var nextStepPromise = getCoursesPromise.then(function(result){
//do what you want to do after this.getCourses
}).catch(function(reject){
console.log(reject);
});
}
您必须决定何时触发resolve()以返回promise对象。