How do I call a service directly in my typescript file in Angular?

Viewed 35

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));
1 Answers

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