-1

Currently I have this working

let cognitoUser: CognitoUser;
        this.userService.cognitoUser.subscribe(
          r => {
            cognitoUser = r;
          }
        );

Is there a one liner like const cognitoUser = ....

Thank you

Stefan
  • 174
  • 1
  • 13
  • There is no one liner like that. Observables are usually asynchronous so you have to account for the asynchronous nature of getting a value. Please describe your problem / use case in more detail. – frido Nov 07 '20 at 00:34

2 Answers2

0

You can use async pipe.

In addition if You are in need of selecting only a single field from object returned by the observable, You can use a pluck operator.

You have a long list of operators to define a logic without having to subscribe for the observable, leaving that job to async pipeline. Another usefull pipe operator might be a map or any other filtering pipe.

Pluck/map will handle object transformation the observable emits and will return its value at the other end of the pipe, async will allow You to not subscribe in the code but rather leave the observable for the markup to subscribe whenever it is needed.

It won't make it as short as You probably want but it is better than nothing:

x.component.ts:

public observable$ = this.userService.cognitoUser;

x.component.html:

{{ observable$ | async }}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Eatos
  • 444
  • 4
  • 12
  • What if I want to use it like cognitoUser.attributes.email in both ts and html file? Thank you – Stefan Nov 07 '20 at 00:26
0

Your cognitoUser is Observable or BehaviourSubject? BehaviourSubject could return this.userService.cognitoUser.value() which means last value of your BehaviourSubject.

Filip
  • 143
  • 1
  • 8