如何以正确的方式订阅 getUrl。 Angular 2

How to subscribe on getUrl in proper way. Angular 2

我有 json 个文件 url。 Alos 有服务,它得到 url 调用 ConfigurationService.ts 和方法:getConfiguration(key);

api 应该像这样工作:获取 url,并在 运行 verifyLogin() 之后使用当前 url; 但是我在订阅方面遇到了问题,我认为有一种更简单的方法。 这是 configurationService.ts:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ConfigurationService {
constructor(private http:Http) {
}
private result: Object;
getConfiguration(key) {
    return this.http.get('./app/config/config.json').map((res: Response) => {
        this.result = res.json();
        return this.result[key];
    });
}
}

这是授权服务:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {HttpBaseClass} from './http_base_class';
import {ConfigurationService} from '../config/configuration_service';

@Injectable ()

export class AuthenticationService extends HttpBaseClass {
result: {
    ok: boolean;
};



private verifyUrl = '';
private logoutUrl = '';

constructor (private http: Http, private configurationService: ConfigurationService) {
    super(http);
}


private authRequest (url) {
    let body = JSON.stringify({});
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({
        headers: headers
    });
    return this.http.post(url, body, options)
        .map((res: Response) => res.json())
        .map(res => {
            this.result = res;
            return this.result.ok;
        });
}
 //test - how to put received url into this.authRequest(this.verifyUrl) ?? 
 //  private x = this.configurationService.getConfiguration("verifyUrl").subscribe((result) => console.log(result));

 //verify runs in appComponent oninit.
verifyLogin() {
    return this.authRequest(this.verifyUrl);
}
logout() {
    return this.authRequest(this.logoutUrl);
}

}

HomeComponent.ts 以防万一:

 ngOnInit() {
   // check isLogged in
  this.isLogged();
}
//check if logged in
isLogged () {
    this.authenticationService.verifyLogin().subscribe((result) => {
        if (result) {
            this.structureRequest.sendRequest().subscribe((result) => this.viewNodes(result));
            //makes http request and puts result into contantArray
        } else if (result === false) {
            this.router.navigate(['/login']);
        }
    });
}

更新: 我尝试以下一种方式设置 verifyLogin() 方法。但是出现错误:"TypeError: this.authenticationService.verifyLogin(...).subscribe is not a function"

verifyLogin() {
  return  this.configurationService.getConfiguration("verifyUrl")
        .subscribe((url) => {
           // this.verifyUrl = url;
            this.authRequest(url);
        });
}

您可以使用缓存和回调重写您的配置服务以动态加载配置数据:

@Injectable()
export class ConfigurationService {
  private _filePath: string = './src/config.json';
  private _configCache: any = null;

  constructor(private _http: Http) { }

  getConfig(key: string, callback: (value) => void) {
    if (this._configCache) {
      return callback(this._configCache[key]);
    }

    this._http.get(this._filePath)
      .map(res => res.json())
      .subscribe(
        (data) => { 
          this._configCache = data;
          callback(this._configCache[key]);
        },
        (error) => {
          console.log("Couldn't load config.");
        },
        () => { console.log(this._configCache); }
      );
  }
}

像这样使用它:

verifyLogin(callback: (data) => void) {
    this.configService.getConfig("verifyUrl", (value) => {
        this.authRequest(value).subscribe((data) => callback(data));
    });
}

你的isLogged方法:

//check if logged in
isLogged () {
    this.authenticationService.verifyLogin((result) => {
        if (result) {
            this.structureRequest.sendRequest().subscribe((result) => this.viewNodes(result));
            //makes http request and puts result into contantArray
        } else if (result === false) {
            this.router.navigate(['/login']);
        }
    });
}

Plunker for example usage