TypeError: Невозможно установить свойство при выполнении переданной функции - PullRequest
0 голосов
/ 05 мая 2018

Я новичок в функциональном программировании. При передаче функции в другую функцию в скрипте типа я получаю сообщение об ошибке. Вот мой код: -

export class NavigationComponent implements OnInit {

  constructor(public globals: Globals, public auth: AuthService, public placeService: PlaceService) {
    auth.handleAuthentication();
    if (auth.isAuthenticated) {
      console.log(' userName ' + this.firstName + ' userName ' + this.userName + ' dp ' + this.dpUrl);
      this.fetchProfile();
      console.log(' userName ' + this.firstName + ' userName ' + this.userName + ' dp ' + this.dpUrl);
    }
  }

  ngOnInit() {
    this.getCountries();
  }

  private firstName: any;
  private userName: any;
  private dpUrl: any;

  private fetchProfile() {
    this.auth.getProfileReponse(this.processResponse);
  }

  public processResponse(userResponse: Observable<HttpResponse<UserResp>>) {
    userResponse.subscribe(resp => {
      const user: User = { ...resp.body }.flatUser;
      console.log('user');
      console.log(user); // printing user perfetcly
      console.log(user.firstName); // printing user perfetcly
      this.firstName = user.firstName; // facing error here
      this.userName = user.userName;
      this.dpUrl = user.dpURL;
      // console.log(this.flatUser);
    });
  }
}

Ошибка, как показано ниже: -

core.js:2090 ERROR TypeError: Cannot set property 'firstName' of undefined
at SafeSubscriber.eval [as _next] (navigation.component.ts:83)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
at SafeSubscriber.next (Subscriber.js:187)
at Subscriber._next (Subscriber.js:128)

почему это 'firstName' не определено, я использую угловую 6 бета-версию. Пожалуйста, помогите мне решить эту проблему.

1 Ответ

0 голосов
/ 05 мая 2018

На самом деле контекст this не определен. Попробуйте вместо этого:

this.auth.getProfileReponse(() => this.processResponse);

Синтаксис стрелки будет привязан к этому, и это должно предотвратить ошибку

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...