2016-09-07 43 views
0

因此,我是OOP的新手,並嘗試使用typecript打印出帶角度2的離子2。 說我有在耦合到用戶名在home.ts這樣Home.html文件中輸入:從angular2中的提供者中的組件訪問屬性

export class HomePage { 
public username: string; 
public newusername: string; 
... 
constructor(public users: UserService) { 
... 

現在我想一個服務(userService.ts)把用戶名從輸入或家庭。並修改它並將結果存儲爲新用戶名。

我是否需要在服務/提供程序中創建一個構造函數,例如在主頁上實例化一個新的對象,儘管我已經在home.ts中創建了這個對象。

我在userServices中導入了HomePage,但無法訪問newusername,因爲我沒有創建它的對象。

+0

你想怎麼userService閱讀的用戶名?當你按下任何按鈕時鍵入或輸入用戶名後? – micronyks

+0

它更多的是一個概念性問題,所以一個按鈕就可以做到。 – solaire

+1

我可以問你爲什麼要從服務中訪問組件屬性_directly_?但它似乎並不是一個好的設計。一個更好的方法是'組件---(調用方法) - >服務---(發送結果)--->組件' – sebaferreras

回答

1

我不知道你到底想要什麼,但如果它對你有好處,請看看這個。 (我會使用newusername在服務本身)

注意:它有沒有關係Ionic2,因爲我不知道Ionic2

工作演示https://plnkr.co/edit/03oXUTZYwRRo8PTfDFlA?p=preview

import { Component } from '@angular/core'; 
import {service} from './service'; 
@Component({ 
    selector: 'my-app', 
    template: ` 
    New User : {{s.newusername}}<br> 
    <input type="text" [(ngModel)]="username"> 
    <button (click)="click(username)">Add User</button> 
    ` 
}) 
export class AppComponent { 

    constructor(private s:service){ 
    } 

    click(username){ 
    this.s.addUserName(username); 
    console.log(this.s.newusername) 
    } 

} 

service.ts

import {Injectable} from '@angular/core'; 

@Injectable() 
export class service{ 

    newusername:string; 
    addUserName(str){ 
    this.newusername=str; 
    } 
} 
1

您需要從組件中的代碼調用服務,或將組件傳遞給服務。

constructor(public users: UserService) {} 

@Input() public username: string; 
// called when an input was updated 
ngOnChanges() { 
    this.newusername = this.users.convertUserName(this.username); 
} 

constructor(public users: UserService) { 
    users.component = this; 
} 

但這仍需要一些方法來通知就像上面的例子中更改輸入服務。

+0

我已經做了類似於你的第一個解決方案,但我想知道是否有一種直接的方式來直接在我的UserService中從home.ts訪問newusername屬性,所以我可以從一個按鈕的html中調用一個方法來將newusername設置爲「xy」。 – solaire

相關問題