0

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

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.