【发布时间】:2018-10-02 03:45:03
【问题描述】:
我是 Angular 新手,正在尝试模拟登录。
我有一个负责对用户进行身份验证的登录组件。在身份验证 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 密钥。这很好还是有更好的解决方案?
谁能告诉我如何在组件之间共享数据?
【问题讨论】:
-
创建服务并在组件之间共享数据或使用 rxjs 主题或行为主题
-
@Chellappan 你能给我举个例子吗?
-
我已经添加了数据共享黑白组件的解决方案stackoverflow.com/questions/52569073/…
标签: angular