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

时间:2016-06-21 07:43:37

标签: angular subscribe

我有带url的json文件。 Alos有服务,它获取名为ConfigurationService.ts的url和方法: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];
    });
}
}

这是auth服务:

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()methid。但是出现错误:“TypeError:this.authenticationService.verifyLogin(...)。subscribe不是函数”

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

1 个答案:

答案 0 :(得分:1)

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

@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例如用法