简体   繁体   中英

Access property from component in provider in angular2

So I'm new to OOP and trying out ionic 2 with angular 2 with typescript. Say I have an input in the home.html file that is coupled to username in home.ts like this:

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.

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?

I imported HomePage in userServices but I cant access newusername because I didnt make an object of it.

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)

NOTE : its has nothing to do with Ionic2 as I don't know Ionic2 .

Working demo : 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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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