getNews(newsType : any){
this.storage.get("USER_INFO").then(right=>{
this.storage.get("sessionkey").then(temp=>{
this.email = JSON.parse(right).email;
this.newkey = temp;
this.authentification =JSON.stringify("Basic " + btoa(this.email+":"+ this.newkey+":"+key));
const body = newsType;
let headers = new Headers({
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': this.authentification
});
let options = new RequestOptions({headers : headers});
return this.http.post('http://api/getNews',body,options)
.map((data:Response) => data.json());
}, err =>{console.log("error on sessionkey",err)})
}, err =>{console.log("error on user",err)})
}
this.httpService.getNews(JSON.stringify(this.category)).subscribe(data => {
this.news = data.News;
});
}, err => {
console.log("Error:", err)
});
我想在嵌套函数成功后调用 API。但是当我在函数成功回调中执行它时,它会给我错误,即类型"void"上不存在属性"订阅"。
如何将 api 的值从服务返回到另一个 .ts 文件
你在这里缺少return
语句:
getNews(newsType : any){
return this.storage.get('USER_INFO').then(right => {
^^^^^^
但是,这仍然会返回没有subscribe
方法的承诺。要将承诺结果包装到可观察量中,您可以使用from
方法:
getNews(newsType : any){
return Observable.from(this.storage.get('USER_INFO').then(right => {
这是对我有用的解决方案。
this.httpService.getNews(JSON.stringify(this.category)).subscribe(data => {
this.news = data.News;
}}, err => {
console.log("Error:", err)
});
getNews(newsType :any) : Observable<any> {
return Observable.create(observer => {
this.storage.get("USER_INFO").then(right=>{
this.storage.get("sessionkey").then(temp=>{
this.email = JSON.parse(right).email;
let authentification =JSON.stringify("Basic " + btoa(this.email+":"+ temp+":"+key));
const body = newsType;
let headers = new Headers({
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authentification
});
let options = new RequestOptions({headers : headers});
this.http.post('http:api/getNews',body,options).subscribe(data =>{
observer.next(data.json());
observer.complete();
});
}, err =>{console.log("error on sessionkey",err)})
}, err =>{console.log("error on user",err)})
}) }
感谢@Maximus和@Theophilus奥莫雷格比
链接:如何在 Angular 2 中创建可观察量