1

I am trying to change the login status after the user login

component.ts

isLoggedIn$: Observable<boolean>; 

  constructor (private auth:Auth){}

  ngOnInit (){


     this.isLoggedIn$ = this.auth.getUser()

     console.log(this.isLoggedIn$);

  }

Auth.ts

@Injectable()
export class Auth {

    private user:boolean = false;

     setUser(){

        this.user= true;
     }

     getUser(){
        return this.user
     }

    removeUser(){
        this.user = false;
    }

}

But i got the following error

error TS2322: Type 'true' is not assignable to type 'Observable'

5
  • You are expecting an Observable of boolean value but returning just a boolean value. This code will make more sense if you are returning Observable from a http call which maps to a boolean value asynchronously. Commented Mar 1, 2018 at 5:10
  • I am mocking http service with Auth class Commented Mar 1, 2018 at 5:12
  • If you are mocking then return Observable.of(this.user) Commented Mar 1, 2018 at 5:14
  • Are you using isLoggedIn$ in your template? If so, you can use it like *ngIf="isLoggedIn$ | async" Commented Mar 1, 2018 at 8:02
  • yes i am using it do i need to add a subscriber to listen the change Commented Mar 1, 2018 at 8:46

1 Answer 1

1

If you are mocking http without an actual service, you can wrap the loggedIn status in an Observable as shown below for a quick fix. Take a look at rxjs and understand Observables for a better understanding.

@Injectable()
export class Auth {

    private user:boolean = false;

     setUser(){

        this.user= true;
     }

     getUser(): Observable<boolean>{
        return Observable.of(this.user)
     }

    removeUser(){
        this.user = false;
    }

}

Also: console.log(this.isLoggedIn$) will not work like that.

Sign up to request clarification or add additional context in comments.

8 Comments

i am getting this error ` Observable_1.Observable.of is not a function at Auth.getUser`
You need to import those. import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of';
You will be better off using Promise + async function in this case.
but why its not update the value?? this component is common to all
How are you using the value? If its in template you can use isLoggedIn$ | async. Else you will have to subscribe
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.