简体   繁体   English

如何在angular2的componenet之间传递用户输入数据?

[英]How to pass user input data between componenets in angular2?

Here's my code, I want to send username input value from login component to home component.I want my username to be updated in constructor so that i can access it in home page. 这是我的代码,我想将用户名输入值从登录组件发送到主页组件。我希望我的用户名在构造函数中进行更新,以便可以在主页中访问它。 How do I assign updated username in constructor? 如何在构造函数中分配更新的用户名?

login.ts 登录名

import {Component, Input,Injectable } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'fountain-tech',
  template: require('./login.html')
})

@Injectable()
export class loginComponent {
       username :any;
constructor(){
this.username  =  username;
}
buttonName:string;

home.ts home.ts

import {loginComponent} from '../login/login'

@Component({
  selector: 'fountain-tech',
  template: require('./home.html')
})
export class HomeComponent {

constructor(public login:loginComponent){
 console.log(this.login.username);
}

I don't get username, it prints undefined in console. 我没有用户名,它在控制台中打印未定义。 There is no problem with provider 提供者没有问题

You can use Input() in your login.ts and then inject it to your home like this: 您可以在login.ts中使用Input() ,然后像这样将其注入到您的家中:

login.ts 登录名

Input() username: any;

and then you can use 然后你可以使用

<app-home [data]="username"></app-home>

you should have data:any; 您应该有data:any; in your home.ts 在你的home.ts中

UPDATE 更新

If you want to use service, you can create a new service for example login.service.ts and define a new variable username:any; 如果要使用服务,则可以创建一个新服务,例如login.service.ts并定义一个新变量username:any; ;。 .

now in your login.ts 现在在您的login.ts中

constructor(private _username:LoginService)
{}

submit(){
  this._username.username = this.username;
}

and in your home.ts constructor 并在您的home.ts构造函数中

constructor(private _username:LoginService)
{
  myUsername = this._username.username
}

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

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