如何通过角度中的行为主题传递多个(2个或多个)变量

时间:2017-12-01 06:18:02

标签: angular rxjs angular5

我是rxjs的新手。在我的应用程序中,我遇到了将用户名和密码值从一个组件传递到另一个组件的情况(角度)。你能帮我把这些变量从一个组件传递到另一个组件,通过行为主题和一个简洁的基本例子。 我有一个存储userdetails的类 UserInformation.ts如下

export class UserInformation {
    username: string;
    constructor() {
    }
}

我有如下服务。 用户information.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中的行为主题将这些变量从第一个组件传递到第二个组件

3 个答案:

答案 0 :(得分:2)

具有如下属性的界面,

export interface School {
    teacher: Teacher;
    student?: Student;
}

private emitter = new Subject<School>();

this.emitter.next({ student: ramStudent, teacher: Anieteacher});

答案 1 :(得分:1)

为什么你需要RxJS用于你的用例?

阅读angular docs中组件之间的通信方式: https://angular.io/guide/component-interaction

如果您不需要提供初始值,则只能使用主题。

一种可能性是通过服务实现这一目标:

export interface ICredentials {
    username: string;
    password: string;
}

@Injectable()
export class UserService {
    private credentials$ = new BehaviorSubject<ICredentials>({
        username: "initial username",
        password: "initial password"
    });

    constructor() {
    }

    public getCredentials(): Observable<ICredentials> {
        return this.credentials$;
    }

    public setCredentials(credentials: ICredentials) {
        this.credentials$.next(credentials);
    }
}

@Component({
    selector: 'dog',
    template: '<div>Bark: Wuff Wuff {{credentials | json}}</div>'
})
export class DogComponent implements OnDestroy {
    private credentials: ICredentials;
    private credentialsSubscription: Subscription;

    constructor(private userService: UserService) {
        this.credentialsSubscription = this.userService.getCredentials().subscribe(credentials => this.credentials = credentials);
    }

    public ngOnDestroy() {
        this.credentialsSubscription && this.credentialsSubscription.unsubscribe();
    }
}

@Component({
    selector: 'user',
    template: '<div>The User ...</div>'
})
export class UserComponent {
    private credentials: ICredentials = {
        username: "my users username",
        password: "my users password"
    };

    constructor(private userService: UserService) {
    }

    public shoutCredentials() {
        this.userService.setCredentials(this.credentials);
    }
}

替代方案,您可以像这样与组件进行通信:

@Component({
    selector: 'information-message',
    template: '<div>My message</div>'
})
export class InformationMessageComponent {
    @Output() public message: EventEmitter<string> = new EventEmitter<string>();
    private myMessage = "Hello World";

    constructor() {}

    public emitMessage() {
        this.message.emit(this.myMessage);
    }
}



@Component({
    selector: 'user',
    template: '<div>Did get message: {{theMessage}}</div> <information-message (message)="onMessage($event)"></information-message>'
})
export class InformationMessageComponent {
    public theMessage: string;

    constructor() {}

    public onMessage(message: string) {
        this.theMessage = message;
    }
}

答案 2 :(得分:0)

在组件1中,您可以执行以下操作:

export class FirstComponent
{
    username:string = "Some Name";
    age:number = "Some Age";
    obs = new Rx.BehaviourSubject();
    obs.next({username: this.username, age: this.age});
}

在您的组件2中,您可以执行以下操作:

export class SecondComponent
{
    constructor(private fc: FirstComponent)
    secondComponentUsername:string;
    secondComponentAge:number;
    subscription = this.fc.obs().subscribe((response) => {
         this.secondComponentUsername = response.username;
         this.secondComponentAge = response.age;
    })
}