0

Here is my code I'm trying to assign data in variable 'user' by setUserDetails function which calls a http provider function fetchUserDetails which returns data as expected. The getUserDetails prints null value.

@Injectable()
export class UserDetailsProvider {
public userChanged = new EventEmitter();
private userUrl = apiUrl+'get_user_details_api';  // URL to web api
public user : any;

constructor(public http: Http, public authService: AuthServiceProvider, public events: Events) {
this.user = null;
}// end of constructor



fetchUserDetails(){
return new Promise((resolve, reject) => {
    let headers = new Headers();
    headers.append('jwt', localStorage.getItem('token'));
    this.http.post(apiUrl+'get_user_details_api', {}, {headers: headers})
      .subscribe(res => {
        resolve(res.json());
      }, (err) => {
        reject(err);
      });
});
}// end of get user details

setUserDetails(){

  this.fetchUserDetails().then((result) => {
   this.user = result;
   console.log(result); // Added this as requested, I told you it's working
    this.events.publish('UserLogged', this.user);
  });
}// end of function

getUserDetails(){
  //console.log(this.user); commenting this out to show the log of http then result
}// end of function

The event publishes the this.user and can be accessed by app component, that's also working fine. I want the user data to be set once at login when the seUserDetails is called and can be accessed the user data anywhere by just calling getUserDetails by returning this.user but it can not access it.

There is the output in console for you ...

Angular is running in the development mode. Call enableProdMode() to enable the production mode.
VM17281 main.js:60356 Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator


VM17281 main.js:33868 Object {user_id: "MEM17042246C9FE2C039", name: "aryan", is_active: "1", is_phone_verified: "1", email:  "amankk92@hotmail.com"…}email: "amankk92@hotmail.com"ifile_name:  "1705051493994229.jpg"ipath: "uploads/MEM17042246C9FE2C039 /profile_pic"is_active: "1"is_phone_verified: "1"login_count: "0"name:  "aryan"user_id: "MEM17042246C9FE2C039"user_type: "3"__proto__: Object
Aman Singh
  • 39
  • 5
  • Could you add a `console.log(result)` in your `then` in the `setUserDetails` function ? Just to see if you get some rsults or not (I assume not if it doesn't work) –  Jun 30 '17 at 08:24
  • Yes I tried that... It's working. Even console.log(this.user) in then seUserDetails also working. I already mentioned that events.publish is working. – Aman Singh Jun 30 '17 at 08:37
  • How have you provided this service, module level or component level? – AT82 Jun 30 '17 at 08:40
  • It's not because events.publish is workign that this.user will be magically set. Please do the console.log(result) and edit your post to show it. Because if events.publish works and your users aren't set, then it's that result is null. –  Jun 30 '17 at 08:40
  • Yes sir, I've provided this service in module level and component level. But that will be used if I'm using this service by some other page.ts – Aman Singh Jun 30 '17 at 09:41
  • @AmanSingh If you have set providers array in component level, it will NOT be a shared service, but all components have an own instance of the service. That is why I asked about if they are in module level or component level. Providers array needs to be only in ngModule so that you have a shared service. – AT82 Jun 30 '17 at 19:51

1 Answers1

0

Could you try this ?

fetchUserDetails(){
let headers = new Headers();
headers.append('jwt', localStorage.getItem('token'));
return this.http.post(apiUrl+'get_user_details_api', {}, {headers: headers})
      .toPromise()
      .then(
          res => Promise.resolve(res.json()), 
          err => Promise.reject(err)
      );
}// end of get user details
  • I don't have a problem in fetchUserDetails function it works fine. The problem is setUserDetails function assigns the user data returned by fetchUserDetails function to this.user. Which is available only in setUserDetails but not in getUserDetails – Aman Singh Jun 30 '17 at 08:34
  • If events.publish works, and your users are null, then your http call is actually returning null. –  Jun 30 '17 at 08:41
  • Events.publish works means it's subscriber is successfully displaying the value of user in page.html dude , it was null then the profile page will not display the username. And for your peace i've added the console output of result. – Aman Singh Jun 30 '17 at 09:40
  • Sorry I wanted confirmation, a lot of people don't even try the responses you give them. Thank you for cooperating. It seems your problem is that you call `getUserDetails` before you set its value. How do you call your getUser and setUser in your components ? –  Jun 30 '17 at 09:42
  • I'm calling setUserDetails while logging in .. in login.ts. Well I also tried calling setUserDetails in app.component.ts in ngOnInit. Even If I call setUserDetails direclty inside getUserDetails the output is still null. Somehow the scope of this.user is limited to getUserDetails only. But in object oriented programming if a class variable is set by one function then the other one can easily access that as far as I know. – Aman Singh Jun 30 '17 at 09:45
  • Well I ... ? And where do you call your getUser function ? –  Jun 30 '17 at 09:48
  • Check above comment. – Aman Singh Jun 30 '17 at 11:15
  • I see ... The only thing that bothers me here and could cause some trouble is your `this.user = null` in the contructor. Otherwise as you said, it should work ... –  Jun 30 '17 at 11:24
  • 1
    If I don't put `this.user = null` in the constructor it will output undefined in console. My head is running wild on this one. – Aman Singh Jun 30 '17 at 15:02