【问题标题】:Fetching a data from a service and display it in the component when it loads/renders : Angular2从服务中获取数据并在加载/渲染时将其显示在组件中:Angular2
【发布时间】:2017-01-02 16:54:45
【问题描述】:

我的服务“MySharedService”中有一个数据,该数据在“MyOutputTemp”中有一个值。我想在组件加载时将其显示在组件中。

这是我的组件:

@Component({

    template: `....
                <p>{{MyOutputHere}}
                .....`

    providers: [MySharedService]

})

export class MyOutputComponent implements OnInit{

    MyOutputHere: string;

    constructor (private _mySharedService: MySharedService){}

    ngOnInit(){
        console.log('Getting value from the service: ' + this._mySharedService.MyOutputTemp); //says undefined
        this.MyOutputHere = this._mySharedService.MyOutputTemp;
        console.log('Value in the component: ' +this.MyOutputHere);//says undefined

    }
}

这是我的服务:

@Injectable()
    export class MySharedService{

        MyOutputTemp: string;

        assignOutput(incomingParameter: string){

            this.MyOutputTemp = incomingParameter;
            console.log('Assigned value: ' + this.MyOutputTemp);
            //the value is successfully assigned and I can get a print 

        } //I am calling it in another component. It is successfully assigning the value. Consider MyOutputTemp has value now.

    }

我尝试了什么:使用 ngOnInit() 从服务中获取值,并将其放在“MyOutputHere”中。 会发生什么: {{MyOutputHere}} 没有显示任何值。如果我在控制台中打印该值,它会显示“未定义”。

这里在概念上是什么错误? 还有,如何从服务中获取 MyOutputTemp 的值并将其显示在组件中?

【问题讨论】:

  • 您还没有调用assignOutput,它为MyOutputTemp 分配了一些值。您应该先调用该函数进行设置。
  • 我在另一个组件中调用它。它正在成功分配值。考虑 MyOutputTemp 有价值。
  • 您是否调试过当ngOnInit 事件在您的组件中触发时是否设置了该值?
  • 是的,我做到了。我尝试在控制台中打印值。它说未定义。
  • ngOnInit 事件在您的组件开始初始化时执行,并且由于某种原因未完成对设置值的调用MyOutputTemp。我建议您改为调用该函数并尝试设置值。

标签: angular typescript


【解决方案1】:

您应该将服务中的MyOutputTemp 变量设为static 变量。

例如:

@Injectable()
export class MySharedService{

    static MyOutputTemp: string;

    assignOutput(incomingParameter: string){

        MySharedService.MyOutputTemp = incomingParameter;

    }
}

在组件中:

export class MyOutputComponent implements OnInit{

    MyOutputHere: string;

    constructor (private _mySharedService: MySharedService){}

    ngOnInit(){
        console.log('Getting value from the service: ' + MySharedService.MyOutputTemp);
        this.MyOutputHere = MySharedService.MyOutputTemp;
        console.log('Value in the component: ' +this.MyOutputHere);
    }
}

这样做的原因是,对于每个组件,都会注入一个新的服务实例。将变量设为静态可确保它在所有实例中都相同。

干杯!

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 1970-01-01
    • 2017-03-16
    • 2016-06-09
    • 2016-08-27
    • 2017-03-07
    • 1970-01-01
    • 2018-01-22
    相关资源
    最近更新 更多