Как правильно подписаться на getUrl. Угловой 2

У меня есть файл json с URL-адресом. У Alos есть служба, которая получает URL-адрес с именем ConfigurationService.ts и метод: getConfiguration (key);

API должен работать следующим образом: получает URL-адрес и после запуска VerifyLogin() с текущим URL-адресом; Но у меня проблемы с подписками, и я думаю, что есть более простой способ. вот конфигурацияService.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 не является функцией"

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

person Serhiy    schedule 21.06.2016    source источник


Ответы (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 для примера использования

person rinukkusu    schedule 21.06.2016
comment
позвольте мне попробовать прямо сейчас. Вы думаете, что this.verifyUrl = url запустится раньше, чем veryfiLogin() ?? - person Serhiy; 21.06.2016
comment
Ну да, может быть состояние гонки, я предложу другое решение через секунду. - person rinukkusu; 21.06.2016
comment
не работает, URL-адрес по-прежнему пуст, когда запускается метод проверки. - person Serhiy; 21.06.2016
comment
verifyLogin () { console.log (url: + this.verifyUrl); вернуть this.authRequest(this.verifyUrl); } URL-адрес пуст. Я думаю, что этот метод запускается до того, как VerifyUrl получает строку. - person Serhiy; 21.06.2016
comment
И да, мы собираемся перезвонить аду, но это единственный способ убедиться, что он поступает в правильном порядке. - person rinukkusu; 21.06.2016
comment
Не могли бы вы также посоветовать мне, как переделать isLogged(). потому что я получаю сообщение об ошибке Не могу прочитать свойство «подписаться» на неопределенное - person Serhiy; 21.06.2016
comment
Рад, что смог помочь! - person rinukkusu; 21.06.2016