我使用了Promise和observables逻辑,使用“get”从服务器获取数据。 它一直工作到昨天。然后它开始抛出上述错误。 请帮我找错。 我得到“通用类型'承诺'需要1个类型的参数”错误。
@Injectable()
export class myBlogService{
// Property to hold root server URL i.e host
private serverUrl:string = "app/data.json"
constructor(private http:Http) {}
// check function in service to check control is coming to service
check(){
alert("getting clicked from service");
}
// get function to get data from server
// basically blog datas
get(): Promise {
return this.http.get(this.serverUrl)
.map(response => response.json())
}
}
/**
*
* My Components
*
*/
@Component({
selector: 'my-app',
providers: [myBlogService],
styleUrls: ['app/css/app.css'],
template: `
<h1 (click)= check()>My First Angular 2 App</h1>
<button (click)=get()>Get My Name</button>
<h1>{{getResponse.name}}</h1>
`
})
export class myBlogApp {
// Property to hold blog data
public getResponse = {"name": "", "age": ""};
constructor(protected myblogservice:myBlogService){}
// check function to check control is going to service
check() {
this.myblogservice.check();
}
// get function calls service get function which return data from server
get(){
this.myblogservice.get().subscribe(data => {
this.getResponse = data;
});
}
}
/**
*
* NgModule Declaration
*
*/
@NgModule({
imports: [ BrowserModule, HttpModule ],
declarations: [ myBlogApp ],
providers: [ ],
bootstrap: [ myBlogApp ]
})
export class app{}
/**
*
* App engine entry point
*
*/
const platform = platformBrowserDynamic();
platform.bootstrapModule(app);
当给出“承诺:”时,它仍会给出类似的问题 “错误TS2339:'Promise'类型中不存在属性'subscribe'。”
我尝试了不同的解决方案,但没有运气。
答案 0 :(得分:14)
您需要添加特定类型。
如果它不包含任何数据且仅用于解析/拒绝功能,请使用:
Promise<void>
最终这是一个类型签名,所以你可以使用:
Promise<any>
https://basarat.gitbooks.io/typescript/content/docs/promise.html
答案 1 :(得分:2)
不要使用Promise
尝试使用Observable
,而是替换:
get(): Promise {
return this.http.get(this.serverUrl)
.map(response => response.json())
}
与
get(): Observable<any> {
return this.http.get(this.serverUrl)
.map(response => response.json())
}