1

我刚刚开始尝试学习 Angular。我熟悉 Angular JS,并决定投身 2+。显然,我开始使用 Angular 6。那是一个很大的飞跃。

当应用程序启动时,我试图从我的 API 获取一些信息。为此,我创建了一个提供程序,并对一些我需要的信息进行了硬编码以使其工作。现在我正在尝试删除硬编码部分并实际从当前位置获取一个 url 段。我尝试过使用路由器,也尝试过使用位置。我不断收到一条消息,说他们没有提供者。我不知道如何解决这个问题。我首选的解决方案不是使用 window.location,而是我可以模拟和/或单元测试的东西。

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Router } from '@angular/router';

import { AppComponent } from './app.component';
import { CoreModule } from './core/core.module';
import { TemplateListComponent } from './template-list/template-list.component';
import { SectionEditorComponent } from './section-editor/section-editor.component';
import { SiteGuidProvider } from './core/siteGuid.provider';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,
    TemplateListComponent,
    SectionEditorComponent
  ],
  imports: [
    BrowserModule,
    CoreModule,
    HttpClientModule,
    RouterModule
  ],
  providers: [
    SiteGuidProvider, {
      provide: APP_INITIALIZER,
      useFactory: siteGuidProviderFactory,
      deps: [SiteGuidProvider],
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

export function siteGuidProviderFactory(provider: SiteGuidProvider){
  return () => provider.load();
}

siteGuid.provider.ts

import { Injectable } from "@angular/core";
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import { HttpClient } from "@angular/common/http";
import { DefaultUrlSerializer, Router, UrlTree } from "@angular/router";

import { environment } from "../../environments/environment";
import { OperationReturn } from "./models/OperationReturn";
import { Site } from "./models/Site";

@Injectable()
export class SiteGuidProvider {
    private siteGuid: string = null;

    constructor(private http: HttpClient,
                private location: Location) {}

    public getSiteGuid(): string{
        return this.siteGuid;
    }

    load(){
        console.log(this.location);
        return new Promise((resolve, reject) => {
            this.http
                .get<OperationReturn>(environment.apiUrl + '/site/name/' + 'ja2')
                .subscribe(response => {
                    this.siteGuid = (<Site>(response.successReturn)).siteGuidString;
                    resolve(true);
                })
        });
    }

    // private getDirectoryName() : string {
    //     let url : UrlTree = new DefaultUrlSerializer(this.router.url);
    // }
}
4

0 回答 0