Angular 2局部变量未定义外部方法

时间:2017-01-18 00:18:45

标签: angular

我有一个奇怪的场景,当我将本地变量分配给来自服务的值时,它会在未定义的consol中打印,但是,在html模板中它会打印该值。

app.component.ts

import { Component, OnInit,Input,ElementRef} from '@angular/core';
import { NavMenuService } from './navmenu/navMenu.service';
import { AppParamasService } from './shared/app-params.service';


@Component({
    selector: 'pm-app',
    moduleId: module.id,
    templateUrl: 'app.component.html',
    providers: [NavMenuService]
})
export class AppComponent implements OnInit {
        pageTitle: any[];
    title: string;
    id: number;
    errorMessage: string;
    constructor(private _navMenuService: NavMenuService, elm: ElementRef, private _appParams: AppParamasService) {

       somecode...
    }

    ngOnInit(): void {

        this._navMenuService.getLinkName(9999)
            .subscribe(
            data => {
                this.id = data.result.LinkID;
                this.title = data.result.LinkName;

            },
            error => this.errorMessage = <any>error);

        this._appParams.SetLinkID = this.id;//value is undefined
        console.log('app component linkid   ' + this.id);



    }

}

我也尝试将设置放在

this._navMenuService.getLinkName(9999)
            .subscribe(
            data => {
                this.id = data.result.LinkID;
                this.title = data.result.LinkName;

                this._appParams.SetLinkID = this.id;//value is undefined
        console.log('app component linkid   ' + this.id);

            },
            error => this.errorMessage = <any>error);

只有我像这样对

这样的值进行硬编码才有效
this.id=9;
this._appParams.SetLinkID = this.id;
console.log('app component linkid   ' + this.id);
app.component.html中的

值正在显示!!

{{ID}}

{{TITLE}}

app-params.service //这是一个共享服务,因此值可供其他组件使用

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import { IAppParams } from './app-params';

@Injectable()


export class AppParamasService {


    params: IAppParams;
    constructor() {

    }

    private _linkID: number;
    get LinkID(): number {
        return this._linkID;
    }
    set SetLinkID(value: number) {
        this._linkID = value;
    }

    private _gwLinkID: number;
    get GWLinkID(): number {
        return this._gwLinkID;
    }
    set SetGWLinkID(value: number) {
        this._gwLinkID = value;
    }


    GetParams() {
       return this.params;
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server Error');
    }
}

为什么我的this.id未定义?

请记住,如果我将消息放在方法中,我会看到值。如果我检查外面的值,所有值都会丢失。 this.title和this.titleID

的saame问题
this._navMenuService.getLinkName(this.linkID)
            .subscribe(
            data => {
                 this.titleID = data.result.LinkID;
                 this.title = data.result.LinkName;
                 this.titleIDString = data.result.LinkName;
                 //all values are printing correctly 
                 console.log('app component link id ' + this.titleIDString);
                 console.log('app component title ' + this.title);
                 console.log('app component link id data' + this.titleID);
            },
            error => this.errorMessage = <any>error);
           //all are undefined
        console.log('app component outside loop link id ' + this.titleIDString);
        console.log('app component outside loop title ' + this.title);
        console.log('app component outside loop link id ' + this.titleID);

我正在尝试存储titleID,以便其他组件可以访问它

ngOnInit(): void {

        this._navMenuService.getLinkName(this.gwLinkID)
            .subscribe(
            data => {
                this.titleID = data.result.LinkID;
                this._appParams.SetLinkID = data.result.LinkID;
                this.title = data.result.LinkName;

                console.log('nav inside link id ' + data.result.LinID);
                console.log('nav inside link id ' + this.titleID );

            },
            error => this.errorMessage = <any>error),

            console.log('nav outside link id ' + this.titleID);
           console.log('nav outside ' + this.title);

            this._appParams.SetParams(this.psnlUID, this.ntName, this.gwLinkID);




            this._navMenuService.getTabs(this._appParams.LinkID, 'xxxx')
            .subscribe(
            data => {
                this.tabs = data.result
            },
            error => this.errorMessage = <any>error),
            this.appParams = this._appParams.GetParams();







    }

this._appParams.LinkID为null,这是一个问题

1 个答案:

答案 0 :(得分:2)

我认为你正在处理一个异步问题。正如您在问题中声明的那样,在订阅之外,值是未定义的,这是真的。这是一个异步操作,因此订阅之外的代码在订阅 in 订阅之前执行,导致它未定义。

this._navMenuService.getLinkName(this.linkID)
            .subscribe(
            data => {
                 // this is executed later than outside subscribe
                 this.titleID = data.result.LinkID;
                 console.log('app component link id data' + this.titleID);
            },
            error => this.errorMessage = <any>error);
           //code here gets executed before inside subscription!
           console.log('app component outside loop link id ' + this.titleID);

编辑:现在看到你的代码,一个解决方案只是链接所有这些请求:

你的ngOnInit调用第一个方法,而在订阅中,调用另一个检索选项卡的方法。

ngOnInit(): void {
    this._navMenuService.getLinkName(this.gwLinkID)
        .subscribe(
        data => {
            this.titleID = data.result.LinkID;
            this._appParams.SetLinkID = data.result.LinkID;
            this.title = data.result.LinkName;
            this._appParams.SetParams(this.psnlUID, this.ntName, this.gwLinkID);
            this.getTabs(); // call the tabs-method here, data is available here!
        });
}

在你的ngOnInit之外:

getTabs() {
    this._navMenuService.getTabs(this._appParams.LinkID, 'xxxx')
        .subscribe(
        data => {
            this.tabs = data.result;
            this.appParams = this._appParams.GetParams();
        });
}