2017-01-30 5 views
3

だから、やっていることは簡単なようです。それはおそらくそうです。しかし、私はそれを理解することはできません。私の質問は:@InputからAngular2コンポーネントのサービスに変数を渡すにはどうすればいいですか? (コードが簡素化されました)@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をダイビングしています。助けや助言をいただければ幸いです。

+0

セッターが働きます。しかし、基本的にあなたは早すぎます。 'ngOnInit(){this.cms.getContent(this.id);}で設定した場合にも動作するはずです。 } ' –

+0

ありがとう@Krisこれは私のために働いたものです。より具体的な回答を追加したいのですか、使用している実際のコードを貼り付けたいのですか? – OGZCoder

+0

よく見えます。あなたは運が良かったですか?それはうまくいくはずです...どちらの方法が正直であることが好ましいか分かりません。 –

答えて

0

を@Krisホレンベック、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 { 

    public content : string; 

    @Input() id : string; 

    constructor(private cms: CMSService) { } 

    ngOnInit() { 
    this.content = this.cms.getContent(this.id); 
    } 
} 

これは、サービスから変数 "content"へのデータと、要素属性から変数 "id"に渡されたIDを割り当てました。両方の変数はテンプレートにアクセスできました。

+0

ありがとうKris。それは私に面白いhella見えた:D – OGZCoder

2

ちょうどそれセッター作成し、そこにコードを置く:

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

詳しい情報なしでここから難しいです。 'textId'にはどこに値を割り当てますか? –

+0

これは、コンポーネント要素の属性によって設定されます。self: – OGZCoder

+0

' OGZCoder

関連する問題