繁体   English   中英

从angular2的提供者中的组件访问属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM