1

In my service class I have a get request that returns an array of strings:

    getStrings$(): Observable<string[]> {
    const url = `test/strings`;
    return this.http.get<string[]>(url, {
    headers: { 'Content-Type': 'application/json' },
    });
    }

In my component ts class I am trying to call the service method directly and get the values:

    readonly getStrings = this.stringSvc.getStrings$;
    constructor(private stringSvc: StringService) {

When I console.log getStrings it is returning just the contents of the service method instead of the values that the service method return in a String array

Edit- how would I call the observable in a method to filter the strings based on if it starts with the input?

this.filteredStrings = 
            this.getStrings
                .filter(ci => ci.toLowerCase().startsWith(query));
Sirth
  • 89
  • 6
  • `StringService.getStrings$` returns the value from `this.http.get` which is `Observable`. You are logging the observable, not any of the emitted values from the Observable. To show what's being returned, you'll need to subscribe to the Observable ([docs](https://angular.io/guide/observables#subscribing)). – D M Sep 06 '22 at 17:16
  • Or, the more modern way would be to bind your template to the Observable and use the [AsyncPipe](https://angular.io/api/common/AsyncPipe) to handle subscribing/unsubscribing for you. You can use the [tap operator](https://rxjs.dev/api/operators/tap) to log the values on their way through the stream. – D M Sep 06 '22 at 17:17

1 Answers1

1

Your service returns an observable. You have to subscribe to the observable to fire it and log the values in the console.

constructor(private stringSvc: StringService) {
   this.stringSvc.getStrings$().subscribe(resp=>{
       this.getStrings = resp;
       console.log(resp);
   });
}
HassanMoin
  • 2,024
  • 1
  • 6
  • 16
  • If you're going to subscribe directly, make sure you implement some kind of unsubscription or you will face memory leaks. See [Angular/RxJS When should I unsubscribe from `Subscription`?](https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription) – D M Sep 06 '22 at 17:19
  • @DM, just a question is it necessary to unsubscribe from HTTP observables as well, using takeUntil etc. or do they unsubscribe/complete by themselves? – HassanMoin Sep 06 '22 at 17:22
  • 1
    You are correct and I was mistaken, it doesn't look like you have to do it for simple subscriptions to HttpClient's methods, but there are some caveats. See [Is it necessary to unsubscribe from observables created by Http methods?](https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods) – D M Sep 06 '22 at 17:28