0

我正在尝试使用后端的 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 对象。我什至怀疑这种方法是否正确。

4

2 回答 2

0

将主题更改为 BehaviorSubject

行为主体

于 2020-10-13T04:38:44.213 回答
0

你可以试试这种设置。

第一个集中式存储库服务,因此您可以控制标头、路径和安全性(如果需要,您还可以在此处使用 POST、PUT、DELETE):-

存储库.service.ts

@Injectable({
  providedIn: 'root'
})
export class RepositoryService {
  constructor(private http: HttpClient) { }

  public getData = (route: string) => {
    return this.http.get(this.createCompleteRoute(route, environment.endPoint), this.generateHeaders());
  }
  private createCompleteRoute = (route: string, envAddress: string) => {
    return `${envAddress}/${route}`;
  }

  private generateHeaders = () => {
    return {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token'
      })
    };
  }
}

然后是获取和设置数据的服务:-

存储-config.service.ts

@Injectable()
export class StoreConfigService {
    protected config: StoreConfig;
    constructor(private repoService: RepositoryService) { }

    public load(): Observable<StoreConfig> {
        return new Observable(observer => {
            if (this.config) {
                observer.next(this.config);
                observer.complete();
            } else {        
               this.repoService.getData(`<url here>`)
                        .subscribe(res => {
                            this.config = res as StoreConfig;
                            observer.next(this.config as StoreConfig);
                            observer.complete();
                        });
                }
            }
        });
    }
}

最后将它绑定在您的组件中(或者您想要访问存储数据的任何地方,每次访问只会调用一次实际的 API,这样您就可以在几乎没有开销的情况下多次调用它):-

constructor(public storeConfigService: StoreConfigService) { 
   // Here or in onInit ... or where ever
    this.storeConfigService.load()
    .subscribe(res => { <Do your stuff here> });
}

于 2020-10-13T03:22:09.173 回答