2017-07-06 45 views
0

我有一個包含名爲url的變量的服務。將變量值傳遞給app.component的角度服務

下面是代碼:

//service.ts 

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class DataService { 

    private url = 'http://someurl.com/'; 

    constructor (private _http:Http){} 

    getDataHttp():Observable<any> { 
    return this._http.get(this.url) 
     .map((response: Response) => <any> response.json()) 
     .do(data => console.log('All: ' + JSON.stringify(data))) 
     .catch(this.handleError); 
    } 

    private handleError(error: Response) { 
    console.error(error); 
    return Observable.throw(error.json().error || 'Server error'); 
    } 

} 

這裏就是我想從服務調用的URL變量文件:

// app.component.ts 

import { Component, OnInit } from '@angular/core'; 
import { DataService } from './data.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent implements OnInit { 

    errorMessage; 
    data; 

    constructor(private service:DataService) {} 

    ngOnInit() { 
    this.service.getDataHttp() 
     .subscribe(data => this.data = data, 
     error => this.errorMessage = <any>error); 

    } 


} 

我的問題是...我怎麼能傳遞從service.ts到app.component.ts的url值?

+2

創建getters&Setters。 –

回答

1

例如添加getter/setter方法DataService

public getUrl(){ 
    return this.url; 
} 

public setUrl(url:string){ 
    this.url = url; 
    return this.url; 
} 

,然後打電話給他們這樣從AppComponent

let url = this.service.getUrl(); 

檢索值,並且:

this.service.setUrl(another_url); 

來設置它。