简体   繁体   English

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

[英]How to share data between angular components?

I am new to angular and trying to simulate a login. 我是新来的有角度的并且尝试模拟登录。

I have a login component which is responsible for authenticating the user. 我有一个登录组件,负责验证用户身份。 In the response of the authenticate web service we are receiving an api key which should be sent in every subsequent request. 在身份验证Web服务的响应中,我们收到一个api密钥,该密钥应在每个后续请求中发送。

Once the user is logged in we change the path from /login to /dashboard. 用户登录后,我们将路径从/ login更改为/ dashboard。

Now in my dashboard component I am inject login component and calling getApiKey function which is returning undefined. 现在,在仪表板组件中,我将注入登录组件并调用getApiKey函数,该函数返回未定义的内容。 Below is the code 下面是代码

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 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())
  }
}

I am thinking of using session storage to set api key and then read the api key from the dashboard component. 我正在考虑使用会话存储来设置api密钥,然后从仪表板组件读取api密钥。 Is this fine or is there a better solution? 这很好还是有更好的解决方案?

Can anyone please tell me how to share data between components? 谁能告诉我如何在组件之间共享数据?

create Service 创建服务

myservice.ts 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);

}

Then in your login component use next method to share value 然后在您的登录组件中使用next方法共享价值

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;
  }
}

Then subscribe inside your dashboard component 然后在您的仪表板组件内订阅

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())
  }
}

In my case, I created auth service which has login(), logout(), authenticated() functions. 在我的情况下,我创建了具有login(),logout()和authenticated()函数的身份验证服务。 And There are 2 components and they use that auth service. 并且有2个组件,它们使用该auth服务。

Furthermore, if you need to implement route path according to the login info. 此外,如果您需要根据登录信息实现路由路径。 You can control them with auth guard ( https://angular.io/guide/router ) 您可以使用auth guard( https://angular.io/guide/router )控制它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM