所以我对Typescript还是陌生的,我不太确定这里发生了什么。我正在构建一个Ionic应用程序,因此在我的provider文件夹中,我有一个provider。在我的两个函数中,如果在它们的开头删除了if语句,则我的首页的TypeScript文件上会显示
错误type '{}' is not assignable to type '[]'
但是当我添加if语句时,它不再给出该错误。
getOneCourse(course){
return new Promise(resolve=>{
let headers = new Headers();
headers.append('Content-type', 'application/json');
this.http.post('http:localhost:8080/api/specificCourse', JSON.stringify(course), {headers: headers})
.map(res=> res.json())
.subscribe(data=>{
resolve(data);
});
});
}
这是没有if语句的那些函数之一,我的打字稿首页文件对应的函数是:
searchCourse(){
let modal=this.ModalCtrl.create(CoursePage);
modal.onDidDismiss(course=>{
if(course)
this.courseService.getOneCourse(course).then((data)=>{
if(typeof(data[0]) === "undefined"){
let alert = this.alertCtrl.create({
title: "oops",
buttons: ["ok"]
});
}
console.log(data);
this.specificCourses= data;
});
});
modal.present()
}
我在其中启动specificCourses = [];较早。
我的提供程序文件中的第二个功能是:
getCourses(){
if (this.data){
return Promise.resolve(this.data)
}
else{
return new Promise(resolve=>{
this.http.get('http://localhost:8080/api/courses')
.map(res=> res.json())
.subscribe(data=>{
this.data = data;
resolve(this.data);
});
});
}
}
那是首字母
if(this.data){
return Promise.resolve(this.data)}
这是造成此问题的原因。 if语句的关键之处是什么?谢谢大家,让我知道是否需要更多信息。
编辑:我应该添加,当我将if语句添加到getOneCourse()函数时,它不仅会给我一门课程,而且会返回所有课程。任何想法为什么会这样?
答案 0 :(得分:0)
在您的服务中,请确保您导入的是正确的HTTP
import { HttpClient } from '@angular/common/http';
确保这也反映在您的主app.module中
import { HttpClientModule } from '@angular/common/http';
在主应用程序模块的导入部分
imports: [
BrowserModule,
HttpClientModule,
IonicModule.forRoot(MyApp)
]
在您的服务中,将getOneCourse更改为:
getOneCourse(course: any): Promise<any> {
let data = JSON.stringify(course);
headers.append('Content-type', 'application/json');
return this.http.post('http:localhost:8080/api/specificCourse', data, {headers: headers}).toPromise();
}
,然后在组件页面上可以这样称呼它:
searchCourse() {
let modal=this.ModalCtrl.create(CoursePage);
modal.present();
modal.onWillDismiss((course: any) => {
if(course) {
this.courseService.getOneCourse(course)
.then((response) => {
if(typeof(response[0]) === "undefined"){
let alert = this.alertCtrl.create({
title: "oops",
buttons: ["ok"]
});
}
console.log(response);
this.specificCourses= response;
})
.catch((error) => {
console.log('Error response ', JSON.stringify(error));
});
}
});
}
对于课程功能,您可以遵循类似的设置:
getCourses(): Promise<any[]> {
return this.http.get('http://localhost:8080/api/courses').toPromise();
}