Angular Observable returns Subscriber instead of JSON and string shows undefined and no result

Viewed 227

ngOnInit function I have defined in the 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
}

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

Only this show undefined two times await this.api.GetSwapi2().subscribe(j => console.log(j));
others cannot see the data in console.log I'm just trying to get data in my app.component.ts.

1 Answers

Found my answer a minor mistake.

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

Problem is in the next .. this.mySubject.next(data.result); its results not result as console.log(data.results) was showing result.

Related