如何在角度分量之间共享数据?

时间:2018-10-02 03:45:03

标签: angular

我是不熟悉Angle并尝试模拟登录的人。

我有一个登录组件,负责验证用户身份。在身份验证Web服务的响应中,我们收到一个api密钥,该密钥应在每个后续请求中发送。

用户登录后,我们会将路径从/ login更改为/ dashboard。

现在在我的仪表板组件中,我将注入登录组件并调用getApiKey函数,该函数返回未定义的内容。下面是代码

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

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

  private user:User = new User();

  private xSSOFamilyId:string = 'BOMO';

  private apiKey:string;

  constructor(private httpClient: HttpClient) { }

  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.apiKey = response.apiKey;
      console.log(this.apiKey)
      window.location.href = "dashboard";
    }, error => {
      console.log("error occured");
    });
  }

  public getApiKey(): string {
    return this.apiKey;
  }
}

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

import {LoginComponent} from "../login/login.component"

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

  constructor(public loginComponent: LoginComponent) { }

  ngOnInit() {
  }

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

我正在考虑使用会话存储来设置api密钥,然后从仪表板组件读取api密钥。这很好还是有更好的解决方案?

谁能告诉我如何在组件之间共享数据?

2 个答案:

答案 0 :(得分:0)

创建服务

myservice.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/from';

@Injectable()
export class MyService {

  thingTwoStream = new Subject();
  ApiKey = new BehaviorSubject<string>(null);

}

然后在您的登录组件中使用下一种方法分享价值

import { Component, OnInit, Injectable } from '@angular/core';
import { User } from '../domain/User';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { LoginResponse } from '../domain/LoginResponse'
import { MyService} from './myservice';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
@Injectable()
export class LoginComponent implements OnInit {

  private user:User = new User();

  private xSSOFamilyId:string = 'BOMO';

  private apiKey:string;

  constructor(private httpClient: HttpClient,private service:MyService) { }

  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.apiKey = response.apiKey;
      console.log(this.apiKey)
      window.location.href = "dashboard";
    }, error => {
      console.log("error occured");
    });
  }

  public getApiKey(): string {
    this.service.ApiKey.next(this.apiKey);
    return this.apiKey;
  }
}

然后在仪表板组件内进行订阅

import { Component, OnInit } from '@angular/core';    
import {LoginComponent} from "../login/login.component"
import { MyService} from './myservice';

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

  constructor(public loginComponent: LoginComponent,private service:MyService) { }

  ngOnInit() {
     this.service.ApiKey.subscribe((data)=>console.log(data))
  }

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

答案 1 :(得分:0)

就我而言,我创建了具有login(),logout()和authenticated()函数的身份验证服务。并且有2个组件,它们使用该auth服务。

此外,如果您需要根据登录信息实现路由路径。 您可以使用身份验证保护(https://angular.io/guide/router

对其进行控制。