属性'subscribe'在角度2中的类型'void'上不存在

时间:2017-07-18 08:04:37

标签: javascript angular typescript ionic2 angular2-services

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'类型上不存在属性'subscribe'的错误。

如何将api的值从服务返回到另一个.ts文件

2 个答案:

答案 0 :(得分:3)

您在此处缺少return声明:

getNews(newsType : any){
    return this.storage.get('USER_INFO').then(right => {
    ^^^^^^

但是,仍然会返回没有subscribe方法的承诺。要将promise结果包装到observable中,可以使用from方法:

getNews(newsType : any){
    return Observable.from(this.storage.get('USER_INFO').then(right => {

答案 1 :(得分:0)

这是对我有用的解决方案。

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 Omoregbee

link:How to create an observable in Angular 2