Search code examples
angularrxjsobservable

How to resolve Type 'Observable<string>' is not assignable to type 'Observable<{ userId: string; partyId: string; }>'


In my angular project I have written following piece of code, but somehow the complier not happy with it, however, I couldnt able to find where exactly I made the mistake in the code:

    public getUser(): Observable<{ userId: string; partyId: string }> {
    return this.userRepository.getLoggedInUser().pipe(
        map((user: User) => {
            const partyId = user.getUniqueClaimValue(this.claimTypesService.partyId);
            this.persistPartyUserClaims(partyId);
            return { userId: user.Id, partyId: partyId };
        }),
        catchError((err) => throwError(() => err)),
        concatMap(({ partyId }) => this.persistPartyUserClaims$(partyId))
    );
}

and the persistPartyUserClaims$ method is below:

    public persistPartyUserClaims$(partyId: string): Observable<string> {
    return this.storageMap.set('partyId', partyId, { type: 'string' }).pipe(concatMap(() => of(partyId)));
}

So I have realized that the line concatMap(({ partyId }) => this.persistPartyUserClaims$(partyId)) inside getUser() method is causing the issue, as soon as I remove the line from the method its works fine. Below I have attached a screenshot of the errors throwing from compiler:

enter image description here

How can I make this getUser() method working?


Solution

  • Your getUser method is suppose to return Observable<{ userId: string; partyId: string }> but your persistPartyUserClaims$ is returning Observable<string> which is called inside concatMap.So you can try returning the Observable<{ userId: string; partyId: string }> from your persistPartyUserClaims$ method so your code will look like

    public getUser(): Observable<{ userId: string; partyId: string }> {
        return this.userRepository.getLoggedInUser().pipe(
            map((user: User) => {
                const partyId = user.getUniqueClaimValue(this.claimTypesService.partyId);
                this.persistPartyUserClaims(partyId);
                return { userId: user.Id, partyId: partyId };
            }),
            catchError((err) => throwError(() => err)),
            concatMap((res) => this.persistPartyUserClaims$(res))
        );
    }
    
    public persistPartyUserClaims$(res:{ userId: string; partyId: string }): Observable<{ userId: string; partyId: string }> {
        return this.storageMap.set('partyId', res.partyId, { type: 'string' }).pipe(concatMap(() => of(res)));
    }