简体   繁体   中英

Angular calling an Array from a service method() to my main component ;

In my api-service.ts i have an array which contains some data in an Array.

 public getData():Observable<any[]>  {

    return  Observable.toString[ObsResult];
  }

Then in my main component i am trying to call getData() method to display data in
main.componenet.html

service.getData().subscribe({result => console.log (result)});

I get the error TypeError: Cannot read property 'subscribe' of undefined

I am guessing this line is wrong but i am not sure what to put here Observable.toString

There are multiple approaches you could use to solve the problem.

Method 1: More Native implementation

public getData(): Observable < any[] > {
  return new Observable(observer => {
    observer.next(ObsResult);
    observer.complete();
  });
}

Method 2: Angular (rxjs) Implementation

public getData(): Observable < any[] > {
  return of(ObsResult);
}

If you have static data

   example: const ObsResult = [1,2,3,4,5];

You can use

public getData():Observable<any[]>  {

    return  Observable.of(ObsResult);
}

then you can subscribe to

service.getData().subscribe({result => console.log (result)});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM