在角度组件之间共享数据

时间:2018-10-04 11:28:08

标签: angular

我想在两个组件之间共享角度数据。我按照herehere的说明进行了操作。以下是我的代码

login.component.ts

import { Component, OnInit } from '@angular/core';
import { User } from '../domain/User';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { LoginResponse } from '../domain/LoginResponse'
import { DataSharingService } from '../service/DataSharingService';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [DataSharingService]
})
export class LoginComponent implements OnInit {

  private user:User = new User();

  private xSSOFamilyId:string = 'BOMO';

  constructor(private httpClient: HttpClient, private dataSharingService: DataSharingService, private router: Router) { }

  ngOnInit() {
  }

  login(): void {

    var authorization:string = 'Basic ' + btoa(this.user.cwopa + ":" + this.user.password);
    var httpHeaders = new HttpHeaders({
      'Authorization': authorization,
      'userId': this.user.cwopa,
      'X-SSO-Family-Id': this.xSSOFamilyId
    });
    this.httpClient.post<LoginResponse>('http://localhost:8081/web-beginner/authenticate', undefined, {headers: httpHeaders}).subscribe(response => {
      this.router.navigate(['dashboard'])
    }, error => {
      console.log("error occured");
    });
  }

  public getApiKey() {
    this.dataSharingService.setData({apikey: '1234'});
  }

}

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { DataSharingService } from '../service/DataSharingService';
import { LoginComponent } from '../login/login.component';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],
  providers: [DataSharingService, LoginComponent]
})
export class DashboardComponent implements OnInit {

  constructor(private dataSharingService: DataSharingService, private loginComponent: LoginComponent) { }

  ngOnInit() {
    this.dataSharingService.currentData.subscribe(data => {
      console.log(data)
    });
  }

  authorize(appName:string): void {
    console.log(this.loginComponent.getApiKey())
  }
}

我在dashboard.component.html中有一个链接。每次单击它时,都会调用onNgInit和authorize函数。

此外,我要在dashboard.component.ts的authorize函数中接收的数据未打印,而onNgInit正在打印期望值。

有人可以告诉我代码有什么问题吗?

2 个答案:

答案 0 :(得分:2)

删除提供程序:登录组件中的[DataSharingService]将DataSharingService添加到app.module.ts提供程序中,这样它将是单例。

不要通过构造函数注入组件。

private loginComponent: LoginComponent

只需使用服务即可共享数据,或者如果DashboardComponent.html包含LoginComponent作为组件,则可以使用@ViewChild作为Sujay的答案。 因此,您可以使用相同的DataSharingService获取api密钥。

答案 1 :(得分:0)

您需要使用chromedriver.exe关键字获取LoginComponent的引用

@ViewChild