Angular Observable 返回订阅者而不是 JSON 并且字符串显示未定义且没有结果

问题描述

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();
  }
}

仅此显示未定义两次await this.api.GetSwapi2().subscribe(j => console.log(j));
其他人无法看到 console.log 中的数据 我只是想在我的 app.component.ts获取数据。

解决方法

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

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) 正在显示结果。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...