[英]Angular 6 sharing data between components using Service
在我的主頁組件中,它是 Dashboard 組件的子組件,布局服務中注入的 object connectedUser 在主頁組件中未定義(主頁組件日志中的主頁用戶 ID 和主頁連接用戶); 這里缺少什么?
主頁.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HomeRoutingModule } from './home-routing.module';
import { HomeComponent } from './home.component';
/**
*
*
*
* @export
* @class AccueilModule
*/
@NgModule({
imports: [
CommonModule,
ReactiveFormsModule,
HomeRoutingModule,
FormsModule
],
declarations: [
HomeComponent
],
providers: [
]
})
export class HomeModule {}
儀表板.component.ts
import { Component, OnInit } from '@angular/core';
import { UserConnected } from 'src/app/models/userConnected';
import { LayoutService } from '../services/layout.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
currentDate: String;
userSaml = new UserConnected();
constructor(public layoutService: LayoutService) { }
ngOnInit(): void {
/* show today's date */
var today = new Date();
this.currentDate = today.getDate() + '/' + (today.getMonth() + 1) + '/' + today.getFullYear();
/* show today's date */
this.layoutService.getConnectedUser().subscribe(
(data) => {
this.userSaml = data;
this.layoutService.connectedUser.matricule = this.userSaml.matricule;
this.layoutService.connectedUser.profil = this.userSaml.profil;
this.layoutService.connectedUser.uid = this.userSaml.uid;
this.layoutService.connectedUser.username = this.userSaml.username;
this.layoutService.connectedUser.city = this.userSaml.city;
},
(err) => {
throw err;
}
);
}
}
app-routine.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AppComponent } from './app.component';
import { DashboardComponent } from './shared/layout/dashboard/dashboard.component';
export const routes: Routes = [
{
path: '',
component: DashboardComponent
, children: [
{
path: '',
loadChildren: './home/home.module#HomeModule'
},
{
path: 'rapport',
loadChildren: '../rapport/rapport.module#RapportModule'
},
{
path: 'admin',
loadChildren: './admin/admin.module#AdminModule'
}
]
}];
@NgModule({
imports: [
RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
主頁.component.ts
import { Component, OnInit } from '@angular/core';
import { LayoutService } from '../shared/layout/services/layout.service';
import { UserConnected } from '../models/userConnected';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(public layoutService: LayoutService) { }
userID: string;
userExists : boolean = false;
connectedUser = new UserConnected;
ngOnInit() : void {
this.connectedUser = this.layoutService.connectedUser;
console.log("home connectedUser" + JSON.stringify(this.connectedUser));
this.userID = this.connectedUser.uid;
console.log("home userID" + this.userID);
this.adminService.verifyUser(this.userID)
.subscribe(
(data) => {
this.userExists = true;
},
(err) => {
this.userExists = false;
}
);
}
}
最后,這是我的布局服務
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '../../../../environments/environment';
import { UserConnected } from 'src/app/models/userConnected';
@Injectable({
providedIn: 'root'
})
export class LayoutService {
connectedUser : UserConnected;
constructor(private http:HttpClient) { }
getConnectedUser(){
return this.http.get<UserConnected>(environment.RAA_ROOT + '/connectedUser');
}
}
LayoutService
的connectedUser導致您的問題
connectedUser : UserConnected = new UserConnected();
這將為您提供 object 類型的UserConnected class,因此您在訪問它時不會收到該錯誤。 快樂編碼.. :)
首先,將 HomeComponent 中的行更改為:
this.connectedUser = this.layoutService.connectedUser;
進入:
this.connectedUser = this.layoutService.getConnectedUser()
由於您尚未在layoutService中分配它,因此layoutService.connectedUser將返回未定義。 請注意, http.get是異步的,因此它返回一個可觀察對象,您需要訂閱它才能在您的組件中使用它(或者如果您想在您的模板中使用它,請使用 asyncPipe)。
更進一步:
this.layoutService.getConnectedUser().subscribe((connectedUser) => { this.connectedUser = connectedUser; })
更多解釋在這里: https://angular.io/tutorial/toh-pt6
我建議更改服務實現並引入更好的緩存:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '../../../../environments/environment';
import { UserConnected } from 'src/app/models/userConnected';
@Injectable({
providedIn: 'root'
})
export class LayoutService {
private _cachedConnectedUser: UserConnected;
constructor(private http:HttpClient) { }
getConnectedUser(): Observable<UserConnected> {
if (this._cachedConnectedUser ) {
return of(this._cachedConnectedUser);
}
return this.http.get<UserConnected>(environment.RAA_ROOT + '/connectedUser')
.map(response => {
this._cachedConnectedUser = response.body;
return this._cachedConnectedUser;
});
}
}
現在您可以始終調用layoutService.getConnectedUser()
來接收 object。您不必處理所有這些局部變量。
您甚至可以像此處解釋的那樣改進這種緩存機制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.