如何将@Input中的变量传递给Angular2组件中的服务>

时间:2017-01-30 21:13:29

标签: javascript angular typescript

所以,我想要做的似乎是微不足道的。它可能是。但我无法弄明白。我的问题是:如何将@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任何帮助或建议将不胜感激!

2 个答案:

答案 0 :(得分:2)

只需将其设置为setter并将代码放在那里:

  @Input() 
  set id(value : string) {
    this.content = this.cms.getContent(value);
  }

答案 1 :(得分:0)

正如@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”。然后模板可以访问这两个变量!