为什么私有字段在TypeScript中的私有方法的私有方法中具有“未定义”值?

时间:2017-03-31 11:18:15

标签: angular typescript

我正在为 angular2 应用开发授权组件:

import { Component, OnInit } from '@angular/core';
import { IAuthData } from './auth-data';
import { IAuthResult } from './auth-result';
import { AuthorizationService } from './authorization.service';
import { NotificationsService } from 'angular2-notifications';

@Component({
    templateUrl: 'authorization.component.html',
    styleUrls: [ 'authorization.component.css' ],
    moduleId: module.id
})
export class AuthorizationComponent implements OnInit {
    private _authorizationService: AuthorizationService;
    private _notificationsService: NotificationsService;

    constructor(private authorizationService: AuthorizationService, private notificationsService: NotificationsService) {
        this._authorizationService = authorizationService;
        this._notificationsService = notificationsService;
    }

    public pageTitle: string = 'AUTHORIZATION';
    public login: string;
    public password: string;

    ngOnInit() : void {

    }

    authorize(): void {
        this._notificationsService.info(this.pageTitle, `Authorization attempt for "${this.login}": sending auth query to the server.`);
        this._authorizationService.authorize(<IAuthData>{ login: this.login, hash: this.password })
            .subscribe(authResult => {
                let message: string = `"${this.login}": ${authResult.message}`;
                if (authResult.isAuthorized) {
                    this._notificationsService.info(this.pageTitle, message);
                }
                else {
                    this._notificationsService.error(this.pageTitle, message);
                }
            });
    }
}

此代码工作正常,但是,在重构目的中,我决定将lambda表达式代码从subscribe移动到单独的方法中:

private processAuthResult(authResult: IAuthData): void {
     let message: string = `"${this.login}": ${authResult.message}`;
                    if (authResult.isAuthorized) {
                        this._notificationsService.info(this.pageTitle, message);
                    }
                    else {
                        this._notificationsService.error(this.pageTitle, message);
                    }let message: string = `"${this.login}": ${authResult.message}`;
                    if (authResult.isAuthorized) {
                        this._notificationsService.info(this.pageTitle, message);
                    }
                    else {
                        this._notificationsService.error(this.pageTitle, message);
                    }
}

自从我这样做以来,字段this._notificationsServiceundefined方法中的值为pocessAuthResult()。我使用这样的方法:

authorize(): void {
            this._notificationsService.info(this.pageTitle, `Authorization attempt for "${this.login}": sending auth query to the server.`);
            this._authorizationService.authorize(<IAuthData>{ login: this.login, hash: this.password })
                .subscribe(this.processAuthResult);
        }

原因是什么?

0 个答案:

没有答案