fireholster
fireholster

Reputation: 640

Return Observable and subscribe in angular

I have an angular service and having issues in setting up some properties (likely my understanding issues).

    @Injectable()
    export class MyService{
    hoHa:MyObj = null;

    someFunction(): Observable<MyObj>{

     return httpClient.get<MyObj[]>('url')
                      .pipe(
                        map(response => response[]),
                        catchError(this.handleError('someFunction', {} as MyObj)                  
                     )

    }
}

How to set the 'hoHa' service property in someFunction GET response? In angularJs, I use to set the 'hoHa' in $http get success response.

How can I just return if the 'hoHa' is already set when someone calls someFunction? In angularJs, I use to return $q.when() if the property is already set

Upvotes: 2

Views: 63

Answers (1)

Igor
Igor

Reputation: 62213

You can use tap and still return the observable to the caller so it can be subscribed to.

@Injectable()
export class MyService{
    hoHa:MyObj = null;

    someFunction(): Observable<MyObj>{
        return httpClient.get<MyObj>('url')
            .pipe(catchError(this.handleError('someFunction', {} as MyObj), tap(result => this.hoHa = result));

    }
}

Upvotes: 2

Related Questions