简体   繁体   English

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

[英]Access property from component in provider in angular2

So I'm new to OOP and trying out ionic 2 with angular 2 with typescript. 因此,我是OOP的新手,尝试使用带有打字稿的angular 2和ionic 2。 Say I have an input in the home.html file that is coupled to username in home.ts like this: 假设我在home.html文件中有一个输入,该输入耦合到home.ts中的用户名,如下所示:

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

Now I want a service (userService.ts) to take username from the input or home.ts and modify it and store the result as newusername. 现在,我希望服务(userService.ts)从输入或home.ts中获取用户名,并对其进行修改并将结果存储为newusername。

Do I have to make a constructor in the service/provider like in Homepage which instantiates a new object of home though I already made an object of this in home.ts? 我是否必须像Homepage中那样在服务/提供程序中创建一个构造函数,以实例化home的新对象,尽管我已经在home.ts中创建了它的对象?

I imported HomePage in userServices but I cant access newusername because I didnt make an object of it. 我在userServices中导入了HomePage,但是由于没有创建它的对象,所以无法访问newusername。

You would need to call a service from code in the component, or pass the component to the service. 您将需要从组件中的代码调用服务,或将组件传递给服务。

constructor(public users: UserService) {}

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

or 要么

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

but this would still need some way to notify the service about changes to the input like in the above example. 但这仍需要某种方式来通知服务有关输入更改的信息,如上例所示。

I don't know what exactly you want but take a look at this if its good for you. 我不知道您到底想要什么,但是如果对您有好处,请看一下。 (I'd use newusername in service itself) (我将在服务本身中使用newusername

NOTE : its has nothing to do with Ionic2 as I don't know Ionic2 . 注意 :它与Ionic2无关,因为我不知道Ionic2

Working demo : https://plnkr.co/edit/03oXUTZYwRRo8PTfDFlA?p=preview 工作演示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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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