【问题标题】:Property 'subscribe' does not exist on type 'void' in angular 2角度 2 中的类型 'void' 上不存在属性 'subscribe'
【发布时间】:2017-12-22 23:22:22
【问题描述】:
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 文件

【问题讨论】:

  • 正如@Maximus 所说,您必须在嵌套函数return this.storage.get("USER_INFO") 内返回父(外部)级别的数据
  • 嘿,如果有帮助,请考虑接受my answer

标签: javascript angular typescript ionic2 angular2-services


【解决方案1】:

您在这里缺少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 => {

【讨论】:

    【解决方案2】:

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

    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

    链接:How to create an observable in Angular 2

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      相关资源
      最近更新 更多