簡體   English   中英

如何將@Input中的變量傳遞給Angular2組件中的服務>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM