【发布时间】:2017-12-01 16:59:39
【问题描述】:
我是 rxjs 的新手。在我的应用程序中,我遇到了将用户名和密码值从一个组件传递到另一个组件的情况(角度)。请您帮助我通过行为主题通过一个简洁的基本示例将这些变量从一个组件传递到另一个组件。 我有一个存储用户详细信息的类 UserInformation.ts如下
export class UserInformation {
username: string;
constructor() {
}
}
我有如下服务。 用户信息.service.ts
import { Injectable } from '@angular/core';
import { UserInformation } from '../UserInformation';
@Injectable()
export class UserInformationService {
userData:UserInformation;
variable:string='ServiceVariable';
constructor() {
this.userData = new UserInformation();
}
getUserData()
{
return this.userData;
}
setUserData(userData:UserInformation)
{
this.userData.username=userData.username;
console.log(this.userData.officeLocation);
}
}
在我的 FirstComponent.ts 中有以下代码。此 getVALuesFromForm 方法用于从表单中获取用户名。
getValuesFromForm()
{
this.enteredUser.username = this.loginform.get('Username').value;
console.log(this.enteredUser.username);
this.service.setUserData(this.enteredUser);
}
在我的 secondComponent.ts 中,我有以下代码。
import { Component, OnInit , Input , Output } from '@angular/core';
import { UserInformation } from '../UserInformation';
import { UserInformationService } from '../services/user-information.service';
import { Injectable } from '@angular/core';
@Component({
selector: 'app-nav-bar-component',
templateUrl: './nav-bar-component.component.html',
styleUrls: ['./nav-bar-component.component.css'],
providers:[UserInformationService]
})
@Injectable()
export class NavBarComponentComponent implements OnInit {
userInfo:UserInformation;
constructor(public service:UserInformationService) {
this.userInfo=service.getUserData();
console.log(service.userData.username);
console.log(this.userInfo.username);
}
ngOnInit() {
}
}
现在我的问题是我们如何借助 Rxjs 中的 Behavior Subject 将这些变量从第一个组件传递到第二个组件
【问题讨论】:
-
在第一个组件中调用 setUserData 时是否出现错误?
-
问题在于,您的两个组件都获得了单独的服务实例。您正在实例 1 中设置值并从实例 2 中获取值