簡體   English   中英

如何在角度分量之間共享數據?

[英]How to share data between angular components?

我是新來的有角度的並且嘗試模擬登錄。

我有一個登錄組件,負責驗證用戶身份。 在身份驗證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密鑰。 這很好還是有更好的解決方案?

誰能告訴我如何在組件之間共享數據?

創建服務

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

}

然后在您的登錄組件中使用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;
  }
}

然后在您的儀表板組件內訂閱

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

在我的情況下,我創建了具有login(),logout()和authenticated()函數的身份驗證服務。 並且有2個組件,它們使用該auth服務。

此外,如果您需要根據登錄信息實現路由路徑。 您可以使用auth guard( https://angular.io/guide/router )控制它們

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM