Angular Observable返回Subscriber而不是JSON,字符串显示未定义且无结果
ngOnInit我在Angular Observable返回Subscriber而不是JSON,字符串显示未定义且无结果,angular,typescript,rxjs,rxjs6,angular12,Angular,Typescript,Rxjs,Rxjs6,Angular12,ngOnInit我在app.component.tsas中定义的功能。 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
app.component.ts
as中定义的功能。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();
}
}
导出类ApiService{
构造函数(私有http:HttpClient){}
mySubject=新主题();
testSubject=新主题();
GetSwapi(){//函数1
this.http.get('https://swapi.dev/api/people/')
.订阅(数据=>{
console.log(data.results);
this.mySubject.next(data.result);
});
}
GetSwapi2():可观察的{//函数2
this.http.get('https://swapi.dev/api/people/')
.subscribe(数据=>{
this.mySubject.next(data.result);
});
this.testSubject.next('woooow');
返回this.mySubject.asObservable();
}
}
只有这个显示未定义的两次等待this.api.GetSwapi2().subscribe(j=>console.log(j))代码>
其他人无法在控制台.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);
});
}
GetSwapi(){//函数1
this.http.get('https://swapi.dev/api/people/')
.订阅(数据=>{
console.log(data.results);
this.mySubject.next(data.result);
});
}
问题在下一个中this.mySubject.next(data.result)代码>其结果
不是结果
作为控制台.log(data.results)
显示结果。等待
是承诺的语法糖。等待订阅没有任何意义。在本例中,您可以从ngOnInit中删除wait的每个实例,而无需更改任何内容。