Angular2 - 家长和孩子通过服务进行沟通

时间:2017-03-01 14:09:04

标签: angular typescript

我正在尝试在子组件之间进行通信,但是通过文档,我需要按服务执行此操作,当我检索服务信息时遇到困难,当我尝试分配订阅返回时,如果我给一个console.log(),它可以工作,现在如果我分配给一个变量,它就不会在之后访问它,给出undefined作为答案。

将信息传递给另一个

的子类
import { Component, OnInit } from '@angular/core';
import {Angular2TokenService, ResetPasswordData } from 'angular2-token';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { AuthService } from '../services/auth.service';


@Component({
selector: 'app-forgot-passoword',
templateUrl: './forgot-passoword.component.html',
styleUrls: ['./forgot-passoword.component.scss']
})
export class ForgotPassowordComponent implements OnInit {
_resetPasswordData: ResetPasswordData = <ResetPasswordData>{};
tenancy:string;
error:string;
private _sub:any;

constructor(
  private _tokenService: Angular2TokenService,
  private _route: ActivatedRoute,
  private _router: Router,
  private _authService: AuthService
) {}


ngOnInit() {
  this._sub = this._route.parent.params.subscribe(
  params=> this.tenancy = params['tenancy']
  )
}

onSubmit(event){
  event.preventDefault();
  this.error = '';
  this._tokenService.resetPassword({
    email: this._resetPasswordData.email,
  }).subscribe(
    res => {
      console.log(this.tenancy);
      this._authService.confirmResetPassword("check your email");
      this._router.navigate([this.tenancy,'signin'])
   },
    error => this.error = "Error aconteceu algo"
  );

  }

}

服务。

  import { Injectable } from '@angular/core';
  import { ActivatedRoute } from '@angular/router';
  import { Location } from '@angular/common';
  import { Angular2TokenService } from 'angular2-token';
  import { environment } from './../../../environments/environment';
  import { Subject } from 'rxjs/Subject'

  @Injectable()
  export class AuthService {
    tenancy: string;
    private resetPasswordConfirmed = new Subject<string>();
    passwordConfirmed$ = this.resetPasswordConfirmed.asObservable();

    constructor(private _tokenService: Angular2TokenService,
      private activateRoute: ActivatedRoute,
      private _location: Location) { }

    init(){
      this.tenancy = this._location.path().split('/')[1];
      let apiBase:string; 
      if(environment.name==='mock'){
        apiBase = `http://${environment.apiEndPoint}`;
      } else {
        apiBase = `http://${this.tenancy}.${environment.apiEndPoint}`;
      }
      this._tokenService.init({
        apiBase: apiBase
      });
    }

    confirmResetPassword(mensagem: string) {
      this.resetPasswordConfirmed.next(mensagem);
    }
  }

将使用服务数据的其他类;

      import { ActivatedRoute, Router } from '@angular/router';
      import { Angular2TokenService, SignInData } from 'angular2-token';
      import { Component, OnInit } from '@angular/core';
      import { AuthService } from '../services/auth.service';
      import { Subscription } from 'rxjs/Subscription'


      @Component({
        selector: 'app-signin',
        templateUrl: './signin.component.html',
        styleUrls: ['./signin.component.scss']
      })
      export class SigninComponent implements OnInit {
        private _signInData: SignInData = <SignInData>{};
        tenancy:string;
        error:string;
        resetPasswordSucess:string;
        _sub: any;
        subscription: Subscription;

        constructor(
          private _tokenService: Angular2TokenService,
          private _route: ActivatedRoute,
          private _router: Router,
          private _authService: AuthService
        ){   
          this.subscription= _authService.passwordConfirmed$.subscribe(
              mensagem =>{ 
                this.resetPasswordSucess = mensagem;
                console.log(mensagem + '  Mensagem');
              }      
            ); 

        }
        ngOnInit() {
          this._sub = this._route.parent.params.subscribe(
            params=> this.tenancy = params['tenancy']
          );
        }

        onSubmit(){

          this.error = '';
          this._tokenService.signIn(this._signInData)
            .subscribe(
              res   => console.log("DEU CERTO"),
              error => console.log(error)
            );

        }
      }

如果在subscribe之外执行console.log(this.resetPasswordSucess),则将变量赋值为UNDEFINED。

如何在变量中分配值,并且每个人都可以在订阅之外看到?

2 个答案:

答案 0 :(得分:1)

当你的ForgotPasswordComponent调用

this._authService.confirmResetPassword("check your email");

您的SignInComponent尚未订阅您服务中的_authService.passwordConfirmed$

不要在AuthService中使用private resetPasswordConfirmed = new Subject<string>();,而是尝试使用private resetPasswordConfirmed = new BehaviorSubject<string>('');private resetPasswordConfirmed = new ReplaySubject<string>();

区别在于Subject是一场火与遗忘。如果订户在其触发时尚未订阅可观察量,则它会错过该值。当新订阅者订阅时,ReplaySubject将重播过去的值。同样,即使未收到下一个值,BehaviorSubject也会在订阅时提供最新值。

来自http://reactivex.io/documentation/subject.html

  

行为主题:   当观察者订阅BehaviorSubject时,它首先发出源Observable最近发出的项(或者如果尚未发出种子/默认值),然后继续发出源Observable稍后发出的任何其他项(或多个)。

     

ReplaySubject:   无论观察者何时订阅,都会向任何观察者发出源Observable发出的所有项目。

希望有所帮助。

答案 1 :(得分:0)

只有在第一次输出passwordConfirmed $

后才会设置

resetPasswordSucess属性