2016-10-05 6 views
0

私はAngular2/Ionic2コードをリファクタリングする過程にあり、私の状況にとってベストプラクティスを知りたがっています。コンポーネント変数をパラメータとして渡す、またはグローバル変数として割り当てる

私は自分のコンポーネント(this.questions)に変数を定義しており、これを自分のサービスメソッドで使用する必要があります。この問題の解決策を見出すには2通りの方法があります。私は、グローバル変数のサービスを使用し、そこにthis.questionsを割り当て、foo.serviceに

  • それとも、私の方法では、引数として私this.questionsコンポーネント変数を渡すに変数にアクセス

    理論的には両方の方法が有効ですが、一般的なコンセンサスは何ですか?数2のために、以下の

    例コード: 私は私のfoo.service.tsで

    @Component({ 
        selector: 'text-answers', 
        templateUrl: 'text-answers.component.html' 
    }) 
    export class TextAnswersComponent implements OnInit { 
    
        questions: Object; 
    
        constructor(public fs: FooService) { 
        this.questions = {1:"foo", 2:"Bar"}; 
        this.fs.doPrint(this.questions) 
        } 
    

    コンポーネントを持っている:

    doPrint(foo){ 
        console.log(foo) 
        }; 
    
  • 答えて

    1

    良い方法は次のようになり、

    宣言質問オブジェクトサービスそれ自体。 他のコンポーネントでも質問オブジェクトを使用したいと仮定します。

    service.ts

    questions:Object; 
    
    doPrint(){ 
        console.log(this.questions) 
    }; 
    

    AppComponent.ts手のための

    export class TextAnswersComponent implements OnInit { 
        constructor(public fs: FooService) { 
        fs.questions = {1:"foo", 2:"Bar"}; 
        this.fs.doPrint(); 
    } 
    
    +0

    ありがとう!私はこれに似た何かをやり終え、私のpage.tsファイルにfs.questionsを割り当てました。 –

    +0

    あなたは大歓迎です! – micronyks

    関連する問題