2016-06-21 2 views
0

J'ai un fichier json avec url. Alos a le service, qui obtient l'URL appelée ConfigurationService.ts et la méthode: getConfiguration (key); L'API devrait fonctionner comme ceci: obtient l'URL, et après l'exécution de verifyLogin() avec l'URL actuelle; Mais j'ai des problèmes avec les abonnements, et je pense qu'il y a un moyen plus simple. ici est configurationService.ts:Comment s'abonner sur getUrl correctement. Angulaire 2

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]; 
    }); 
} 
} 

ici est le service 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 juste au cas où:

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']); 
     } 
    }); 
} 

MISE À JOUR: Je Nous avons essayé de configurer verifyLogin() methid de la manière suivante. Mais l'erreur apparaît: « Erreur de type:. This.authenticationService.verifyLogin (...) n'est pas s'abonner fonction »

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

Répondre

1

Vous pouvez réécrire votre service de configuration avec un cache et rappel pour charger dynamiquement les données de configuration:

@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); } 
    ); 
    } 
} 

Utilisez-le comme suit:

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

Votre méthode 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

+0

laissez moi essayer maintenant. Vous pensez que this.verifyUrl = url sera exécuté en premier par veryfiLogin() ?? – Serhiy

+0

Eh bien, oui, il pourrait y avoir une condition de course, je proposerai une solution différente dans une seconde. – rinukkusu

+0

ne fonctionne pas l'URL est toujours vide lorsque la méthode de vérification s'exécute. – Serhiy