所以,我正在尝试做的事情似乎微不足道。它可能是。但我想不通。我的问题是:如何将变量从 @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);
}
关于javascript - 如何将变量从@Input 传递到 Angular2 组件中的服务>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41945497/