我想在两个组件之间共享角度数据。我照解释的做了
here
和
here
登录.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'});
}
}
仪表板.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函数中要接收的数据是print undefined,onNgInit正在打印期望值。