2016-08-15 91 views
0

我試圖從http.get訪問WEB API,但它不工作這是我使用observable的服務,但它根本不工作,既不向服務器發送呼叫也不顯示任何錯誤也是如此。observables無法在webapi上工作angular 2

@Injectable() 
export class SetupServiceObservables { 

    public apiServiceBaseUri = 'http://localhost:3000/'; 

    private authheaders: any = {}; 
    private config: any = {}; 
    private auth: any = {}; 

    constructor(private http: Http, private ngWEBAPISettings: WebAPISettings, private authService: AuthService, private router: Router) { 

    } 

    public get(servicename: string): Observable<any> { 
     return this.http.get(this.ngWEBAPISettings.apiServiceBaseUri + "api/" + servicename + "/", this.getConfig()) 
      .map(this.extractData) 
      .catch(this.handleError);; 
    } 

    public getConfig() { 
     this.authheaders.Authorization = this.auth.access_token == "" ? "" : 'Bearer ' + this.auth.access_token; 
     this.config = { 
      headers: { 
       'Authorization': this.authheaders.Authorization 
      }, 
      cache: false, 
     }; 
     return this.config; 
    } 



    private extractData(res: Response) { 
     let body = res.json(); 
     console.log(res); 
     return body.data || {}; 
    } 


    private handleError(error: any) { 
     let errMsg = (error.message) ? error.message : 
      error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
     console.error(errMsg); // log to console instead 
     return Observable.throw(errMsg); 
    } 
} 

回答

1

可觀察是冷的,所以你必須調用subscribe

樣品服務implmentation看起來像這 -

getEmployees(): Observable<{}> { 
     return this._http.get(this._webApiUrl) 
      .map((response: Response) => <any[]> response.json()) 
      .catch(this.handleError) 
      ; 
    } 

從組件,您可以訂閱喜歡這個 -

this._webApiService.getEmployees().subscribe(
       emplist => this.employees = emplist, 
       error => this.errorMessage = <any>error 
       ); 

看看這是否有幫助。

+0

感謝您的幫助,我沒有訂閱他們 – rashfmnb