[英]Timing issue: How can I get the correct value of a variable from angular2 service
[英]How can I pass a variable from @Input to a service in an Angular2 component>
所以,我想要做的似乎是微不足道的。 它可能是。 但我无法弄明白。 我的问题是:如何将@Input中的变量传递给Angular2组件中的服务? (代码已简化)
我的组件如下:
import { Component, Input } from '@angular/core';
import { CMSService } from '../cms.service';
@Component({
selector: 'cmstext',
templateUrl: './cmstext.component.html',
styleUrls: ['./cmstext.component.css']
})
export class CMSTextComponent {
constructor(private cms: CMSService) { }
@Input() id : string;
content = this.cms.getContent(this.id); // this.id is NULL so content is NULL
}
然后我的服务:
import { Injectable } from '@angular/core';
@Injectable()
export class CMSService {
constructor() { }
getContent(textId:string) : string {
this.text = textId; // textId is NULL so this.text returns NULL
return this.text;
}
}
我的组件模板:
<p>id: {{id}}</p>
<p>Content: {{content}}</p>
当<cmstext id="4"></cmstext>
添加到另一个组件模板时,输出为:
id: 4
content:
我只是潜入Angular2任何帮助或建议将不胜感激!
只需将其设置为setter并将代码放在那里:
@Input()
set id(value : string) {
this.content = this.cms.getContent(value);
}
正如@Kris Hollenbeck指出的那样, ngOnInit()
就是答案。 我的最终代码看起来像这样。 该组件现在将变量传递给服务。
import { Component, Input, OnInit } from '@angular/core';
import { CMSService } from '../cms.service';
@Component({
selector: 'cmstext',
templateUrl: './cmstext.component.html',
styleUrls: ['./cmstext.component.css']
})
export class CMSTextComponent implements OnInit {
public content : string;
@Input() id : string;
constructor(private cms: CMSService) { }
ngOnInit() {
this.content = this.cms.getContent(this.id);
}
}
这将服务中的数据分配给变量“content”,并将id从element属性传递给变量“id”。 然后模板可以访问这两个变量!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.