angular 2+从提供者中获取位置

时间:2018-05-08 05:21:05

标签: angular-providers

我刚开始尝试学习Angular。我熟悉Angular JS,并决定将其投入2+。显然,我开始使用Angular 6.这真是一个跳跃。

我正在尝试在应用程序启动时从我的API获取一些信息。为此,我创建了一个提供程序,并对我需要的一些信息进行了硬编码以使其正常工作。现在我正在尝试删除硬编码部分,并实际从当前位置获取网址段。我尝试过使用Router,我尝试过使用Location。我不断收到他们没有提供者的消息。我不知道如何解决这个问题。我首选的解决方案不是使用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);
    // }
}

0 个答案:

没有答案