需要帮助将变量传递给Angular 2中的对话框

时间:2018-06-02 13:26:30

标签: javascript html angular

尝试将用户所在的最后一页的URL ID传递给我可以在对话框中引用的服务。

issuer.service.ts

import { Injectable, EventEmitter } from '@angular/core';
import { Observable, of } from 'rxjs';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class IssuerService {

private urlidSource = new BehaviorSubject<string>('');
currentUrlid = this.urlidSource.asObservable();
public onChange: EventEmitter<string> = new EventEmitter<string>();

  constructor() {
  }

  changeUrlid(urlid: string) {
    this.currentUrlid = of(urlid);
    this.onChange.emit(urlid);
  }


}

具有我想要的网址ID的网页(dashboard.component.ts)

import { IssuerService } from './../../issuer.service';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
urlid: string;
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private issuerService: IssuerService,
    public dialog: MatDialog
  ) {}

newUrlid() {
  this.issuerService.changeUrlid(this.route.snapshot.paramMap.get('id'));
  console.log(this.urlid);
}

  ngOnInit() {
    // Get URL ID
    this.issuerService.onChange.subscribe(urlid => this.urlid = urlid);
    this.newUrlid();
}

组件我想读取以下值:

import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { IssuerService } from './../../issuer.service';

    urlid: string;

    constructor(
      private route: ActivatedRoute,
      private router: Router,
      private issuerService: IssuerService,
      public dialog: MatDialog
    ) {}

  ngOnInit() {
    this.issuerService.onChange.subscribe(urlid => this.urlid = urlid);
console.log(this.urlid);
console.log(this.urlid);
console.log(this.urlid);

  }

所有这3个console.log都以未定义的形式返回。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您需要将 console.log 置于订阅

   this.issuerService.onChange.subscribe(urlid => {
           this.urlid = urlid;
           console.log(this.urlid);
   });