我正在尝试使用后端的 API 加载应用程序级变量,这些变量将在整个应用程序中使用。同样,我使用了解析器,但在加载任何组件之前仍然没有加载该服务,这是我的代码:
pub.global.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CustomUrlBaseService } from './auth/customurlbase';
import { Observable, Subject } from 'rxjs';
import { Resolve } from '@angular/router';
@Injectable()
export class PubService extends CustomUrlBaseService implements Resolve<any> {
appRoot = '/api/pub';
StoreData = '';
private loadPub = new Subject<any>();
loadPubObservable$ = this.loadPub.asObservable();
constructor(private http: HttpClient) {
super();
}
resolve() {
this.GetStoreData();
}
GetStoreData() {
this.GetData().subscribe(res => {
this.StoreData = res;
console.log(res);
})
}
GetData(): Observable<any> {
const url = (`${this.baseURL + this.appRoot}/GetStoreData`);
return this.http.get(url);
}
}
pub-footer.component.ts
import { PubService } from './../../services/pub.global.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-pub-footer',
templateUrl: './pub-footer.component.html',
styleUrls: ['./pub-footer.component.scss']
})
export class PubFooterComponent implements OnInit {
copyrightinfo;
constructor(private pubService: PubService) { }
ngOnInit() {
console.log(this.pubService.StoreData);
const FooterData = this.pubService.StoreData;
this.copyrightinfo = FooterData['copyrightinfo'];
}
}
app.routing.ts
{
path: '',
component: PubLayoutComponent,
loadChildren: () => import('./views/pub/pub.module').then(m => m.PubModule),
data: { title: '' },
resolve: { items: PubService }
},
我也尝试了 app_initializer,现在我的 api 被调用了两次,但在加载组件之前没有被调用:在我的 module.ts
PubService, {
provide: APP_INITIALIZER, useFactory: initApp, deps: [PubService], multi: true
}
export function initApp(initService: PubService) {
return () => {
initService.GetStoreData();
}
}
我的总体想法是在一次 api 调用中加载页眉和页脚信息并存储在服务变量中,然后从页眉和页脚组件中访问这个 json 对象。我什至怀疑这种方法是否正确。