[英]Access property from component in provider in angular2
因此,我是OOP的新手,嘗試使用帶有打字稿的angular 2和ionic 2。 假設我在home.html文件中有一個輸入,該輸入耦合到home.ts中的用戶名,如下所示:
export class HomePage {
public username: string;
public newusername: string;
...
constructor(public users: UserService) {
...
現在,我希望服務(userService.ts)從輸入或home.ts中獲取用戶名,並對其進行修改並將結果存儲為newusername。
我是否必須像Homepage中那樣在服務/提供程序中創建一個構造函數,以實例化home的新對象,盡管我已經在home.ts中創建了它的對象?
我在userServices中導入了HomePage,但是由於沒有創建它的對象,所以無法訪問newusername。
您將需要從組件中的代碼調用服務,或將組件傳遞給服務。
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;
}
但這仍需要某種方式來通知服務有關輸入更改的信息,如上例所示。
我不知道您到底想要什么,但是如果對您有好處,請看一下。 (我將在服務本身中使用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)
}
}
服務
import {Injectable} from '@angular/core';
@Injectable()
export class service{
newusername:string;
addUserName(str){
this.newusername=str;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.