2016-01-21 25 views
0

我有這個服務作爲提供商:如何將一個參數添加到將在組件的構造函數中作爲privider解析的服務?

export class Print { 
 
    text: string; 
 

 
    constructor(text: string) { 
 
    this.text = text; 
 
    } 
 

 
    printText() { 
 
    //dosomething with the text; 
 
    } 
 

 
    prettifyText() { 
 
    //dosomething with the text; 
 
    } 
 
}

在我的部分,我想在角在text解析作爲參數使供應商的一個實例。

const text = 'Something to be printed'; 
 

 
export class AppComponent { 
 
    // How to parse 'text' as an argument 
 
    // to the printService when it is instantiate 
 
    // by angular componennt? 
 
    constructor(printService: Print) { 
 
    printService.prettifyText(); 
 
    printServoce.printText(); 
 
    } 
 
}

+0

你的組件中的文本來自哪裏? – Sasxa

+0

說這是一些全球性的文本(配置文件) –

回答

3

我以爲,問題是如何提供的構造函數值在注入(提供)服務。如果你需要的,是更高級的,想想看:

@Injectable() 
export class Print { 
text: string; 

constructor(text: string) { 
    this.text = text; 
    let injector = Injector.resolveAndCreate([HTTP_PROVIDERS]); 
    let http = injector.get(Http); 

    http 
     .get(this.text + ".json") 
     .subscribe(
      (response: any) => this.text = response.text(), // success 
      null, // error 
      () => console.log("c")// complete 
     ); 
} 
} 

注射器從angular2 /核心,HTTP和HTTP_PROVIDERS從angular2/HTTP 在您的組件裝飾:

@Component({ 
    selector : "cmp-name", 
    providers: [provide(Print, { useFactory:() => { return new 
Print("hello"); }})] 
}) 

而且在CMP名的構造

constructor(public print: Print) {} 

如果CONSOLE.LOG打印,您將獲得:

Print {text: "hello"} 
+0

其實這是正確的答案,因爲printText()方法不應該採用設計參數,所以我已經學會了這種高級技術,謝謝! –

+0

如果我想要獲取con,useFactory:()=> {}'裏面如何使用http服務來自本地/遠程服務器的fig.json? –

+0

您必須使用文本值進行該調用? –

1

你必須有text可以在您的組件,一旦你做,你可以打電話給你的服務的方法:

export class AppComponent { 
    text; 
    constructor(private printService: Print, private http: Http) { 
    // you can get text through http, for example 
    this.http 
     .get('story.txt') 
     .subscribe(
     response => this.text = response.text(), // success 
     null, // error 
     () => this.print() // complete 
    ) 
    } 
    print() { 
    this.printService..printText(this.text) 
    } 
} 
+0

感謝您的更好的結構,我確實需要重構我的代碼。 –

+1

歡迎您(嘗試避免從構造函數中執行任何操作,僅使用它來設置東西,並將您的應用程序邏輯移動到其他位置) – Sasxa

+0

The Angular [tutorial](https://angular.io/docs/ ts/latest/tutorial/toh-pt4.html)建議在構造函數中保留「複雜的邏輯,特別是任何可能調用服務器的東西。構造函數用於簡單的初始化,比如將構造函數參數連接到屬性。」所以我建議把http調用在'ngOnInit()'。 –

相關問題