如何在角度2的组件之间传递用户输入数据?

问题描述 投票:0回答:1

这是我的代码,我想将登录组件的用户名输入值发送到home组件。我希望我的用户名在构造函数中更新,以便我可以在主页中访问它。如何在构造函数中分配更新的用户名?

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

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);
}

我没有获得用户名,它在控制台中打印undefined。提供者没有问题

angular dependency-injection
1个回答
2
投票

您可以在login.ts中使用Input()然后将其注入您的家中,如下所示:

login.ts

Input() username: any;

然后你可以使用

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

你应该在你的家里有data:any;

UPDATE

如果要使用服务,可以创建新服务,例如login.service.ts并定义新变量username:any;

现在在你的login.ts

constructor(private _username:LoginService)
{}

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

并在你的home.ts构造函数

constructor(private _username:LoginService)
{
  myUsername = this._username.username
}
© www.soinside.com 2019 - 2024. All rights reserved.