0

Below code is for login functionality. And in this response I got whole data of particular user. I want to store whole data of current user and use it in other page for edit profile.

login(username: string, password: string): Observable<boolean> {
    var body = 'username=' + username + '&password=' + password;
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.loginUrl, body, options)
        .map((response: Response) => {
            let success = response.json() && response.json().success;
            if (success) {
                this.token = success;
               user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success }));
                return true;
            } else {
                return false;
            }
        });
}
Krunal
  • 938
  • 2
  • 10
  • 33

1 Answers1

0

Seeing a bit of TypeScript, I believe this is Angular (not AngularJS, although not sure).

With Angular, you can achieve this by creating a service and providing it at the module level providers.

In your app.module.ts, register the service as:

@NgModule({
      imports: [BrowserModule, FormsModule, HttpModule ], 
      declarations: [AppComponent],
      bootstrap: [AppComponent],
      providers: [
          MyGlobalService
      ]
})

create this service and inject is a dependency in the corresponding component/service/directive where your login function is. Thereafter once on receiving data, you can store it into the service like:

    if (success) {
            this.token = success;
           user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify({ username: 
            username, token: success }));
            this.myGlobalService.setUserData(response);
            return true;
        }

Of course you will have to implement setUserData function in the service. Like:

@Injectable()
export class MyGlobalService{

private userData :any;

  setUserData(data){
    this.userData = data;
  }

  getUserData(){
    return this.userData
  }
}

Once you have setup like above you should be able to inject the MyGlobalService everywhere in your application and should get the data using the instance of the service like :

let userDataStored = this.myGlobalServcie.getUserData();

Hope it helps.

Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82