2016-09-07 3 views
0

私はOOPを初めて使い、typescriptで角度2のイオン2を試してみました。今、私は入力または自宅からユーザー名を取るためにサービス(userService.tsを)したいangle2のプロバイダのコンポーネントからのアクセスプロパティ

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

: は、私はこのようなhome.tsでユーザ名に結合されているhome.htmlファイルに入力を持っていると言います。それを修正し、その結果をnewusernameとして保存します。

私はすでにhome.tsでこのオブジェクトを作成しましたが、ホームの新しいオブジェクトをインスタンス化するHomepageのようなサービス/プロバイダでコンストラクタを作成する必要がありますか?

私はuserServicesでホームページをインポートしましたが、私はそのオブジェクトを作成しなかったためnewusernameにアクセスできません。

+0

:デモ作業

?あなたが入力すると、または任意のボタンを押すと、ユーザー名を入力した後に? – micronyks

+0

ボタンがそれをするように、より概念的な質問です。 – solaire

+1

なぜサービスからコンポーネントのプロパティ_directly_にアクセスしたいのですか?しかし、それは良いデザインではないようです。より良いアプローチは 'コンポーネント---(メソッドを呼び出す) - >サービス---(結果を送信する)--->コンポーネント' – sebaferreras

答えて

1

私はあなたが何をしたいのか分かりませんが、あなたのためにこれを見てください。その私がIonic2を知らないようIonic2とは何の関係もありません:

NOTEを(私はサービス自体にnewusernameを使用すると思います)。 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あなたはUserServiceのユーザー名を読みたいか

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プロパティにアクセスする直接的な方法があるかどうか疑問に思うので、newusernameを "xy"に設定するボタンからhtmlのメソッドを呼び出すことができます。 – solaire

関連する問題