javascript - 如何将变量从@Input 传递到 Angular2 组件中的服务>

标签 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,如有任何帮助或建议,我们将不胜感激!

最佳答案

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

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

关于javascript - 如何将变量从@Input 传递到 Angular2 组件中的服务>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41945497/

相关文章:

javascript - 如何在 d3.js (v7) 的折线图中只缩放 X 轴

javascript - Angular:EventEmitter 的事件未通过 .subscribe 成功接收

javascript - Angular electron mysql create connection 不是一个函数

typescript : how to declare an enum across multiple files?

javascript - 加载模板时调用操作函数(Ember.js)

javascript - 如何在 NiFi 中调用远程 REST 服务

javascript - 动态 jQuery 使用基于元素的 AddMethod 验证错误消息

angular - <mat-dialog-title> 和 <mat-dialog> 不被识别,但 <mat-dialog-actions> 和 <mat-dialog-content> 被识别

typescript - 静音/忽略来自 TypeScript tsc 的 TS2307 错误

javascript - 使用 JavaScript 的 Selenium Webdriver,如何使用 chrome.exe 的特定路径启动 Chrome?