【问题标题】:Angular Observable returns Subscriber instead of JSON and string shows undefined and no resultAngular Observable 返回订阅者而不是 JSON,字符串显示未定义且无结果
【发布时间】:2021-08-07 21:44:13
【问题描述】:

ngOnInit 函数我在app.component.ts 中定义为。

async ngOnInit(){    
    await this.api.GetSwapi()
    await this.api.mySubject.subscribe(data => console.log); //Not getting data in console log
    await this.api.mySubject.subscribe((data: any) => console.log); //Not getting data in console log
    console.log('---------------------123123123-----------------------');//working
    await this.api.GetSwapi2().subscribe(j => console.log(j)); //Getting undefined two times
    await this.api.testSubject.subscribe(data => console.log); //Not getting data in console log
}

这是我的api.service.ts

export class ApiService {  
  constructor(private http: HttpClient) { }

  mySubject = new Subject();
  testSubject = new Subject<string>();

  GetSwapi(){ //FUNCTION 1
    this.http.get<any>('https://swapi.dev/api/people/')    
    .subscribe(data => {
        console.log(data.results);
        this.mySubject.next(data.result);        
    });
  }

  GetSwapi2(): Observable<any> { //FUNCTION 2
    this.http.get<any>('https://swapi.dev/api/people/')
    .subscribe(data => {        
        this.mySubject.next(data.result);        
    });
    this.testSubject.next('woooow');
    return this.mySubject.asObservable();
  }
}

仅此显示 undefined 两次 await this.api.GetSwapi2().subscribe(j =&gt; console.log(j));
其他人看不到console.log中的数据 我只是想在我的app.component.ts 中获取数据。

【问题讨论】:

  • await 是 promise 的语法糖。对await 订阅没有任何意义。在此示例中,您可以从 ngOnInit 中删除每个 await 实例,而无需更改任何内容。

标签: angular typescript rxjs rxjs6 angular12


【解决方案1】:

发现我的回答有一个小错误。

GetSwapi(){ //FUNCTION 1
    this.http.get<any>('https://swapi.dev/api/people/')    
    .subscribe(data => {
        console.log(data.results);
        this.mySubject.next(data.result);        
    });
  }

问题在下一个 .. this.mySubject.next(data.result); 它的results 不是result 因为console.log(data.results) 正在显示结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2021-09-28
    • 2017-09-03
    • 2018-03-15
    • 1970-01-01
    • 2021-07-05
    • 2021-09-02
    相关资源
    最近更新 更多