Ionic 2 - не может получить доступ к значению, назначенному провайдером http другими функциями в angular 2

Вот мой код, который я пытаюсь присвоить данным в переменной 'user' с помощью функции setUserDetails, которая вызывает функцию http-провайдера fetchUserDetails, которая возвращает данные, как и ожидалось. GetUserDetails печатает нулевое значение.

@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

Событие публикует this.user и может быть доступно компоненту приложения, который также работает нормально. Я хочу, чтобы пользовательские данные устанавливались один раз при входе в систему при вызове seUserDetails, и к ним можно получить доступ к пользовательским данным в любом месте, просто вызвав getUserDetails, вернув this.user, но он не может получить к нему доступ.

Для вас есть вывод в консоль...

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

1 ответ

Не могли бы вы попробовать это?

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
Другие вопросы по тегам