-2

I used this method for binding but when I reload the page its working stop

<div><h1>{{userdata?.firstname}}</h1></div> 

export class HomeComponent {

    constructor(private authenticationService : AuthenticationService) {
        userdata=this.authenticationService.user_data;
    }
}
11
  • What actually is your concern? Can you post your code Commented Jun 20, 2017 at 6:35
  • 1
    a LOT of code is missing. First of all, do you have a component ? Commented Jun 20, 2017 at 6:35
  • As I mentioned in the previous question, try logging your userdata after you assigned it in your constructor. All the ? (elvis operator) does is ensure that the object exists, then it'll go for the sub object. It's important to see what's in your object as it may not have the right field, or your authenticationService may not be returning anything. Commented Jun 20, 2017 at 6:37
  • Also, can we see the code for the authenticationService? Commented Jun 20, 2017 at 6:39
  • but its working every time before reload the page Commented Jun 20, 2017 at 6:39

1 Answer 1

1

Your service could look something like this...

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class AuthenticationService {
  private _user_data: BehaviorSubject<any> = new BehaviorSubject<any>(null);

  constructor() {
    this._restoreUser()
  }

  get user_data(): Observable<any> {
    return this._user_data.asObservable();
  }

  private _restoreUser(): void {
    let user: any;
    // use any code to restore user from cache and assign it to the scoped user variable
    this._user_data.next(user);
  }
}

And in your home component...

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

export class HomeComponent implements OnInit, OnDestroy {
  public userdata: any;
  private _userdataSub: Subscription;

  constructor(private authenticationService: AuthenticationService) { }

  ngOnInit() {
    this._userdataSub = this.authenticationService.user_data.subscribe((userdata) => {
      this.userdata = userdata;
    });
  }

  ngOnDestroy() {
    this._userdataSub.unsubscribe();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.