2016-08-15 75 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