基本角度2认证

时间:2017-06-19 11:03:53

标签: angular

我通过localhost调用一个简单的get请求。我不知道代码有什么问题。我查了很多次。它没有发现任何错误。有人检查我的代码告诉我什么我失踪了。

import { Injectable } from '@angular/core';
 import { Http, Response,Headers,RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    //private _productUrl = 'api/products/products.json';
    //private _productUrl = 'http://localhost:8092/openmrs-standalone/ws/rest/v1/concept';
    private _productUrl = 'http://localhost:8092/openmrs-standalone/ws/rest/v1/session';

    constructor(private _http: Http) { }

    getProducts(): Observable<any> {

         let username: string = 'admin';
         let password: string = 'Admin123';
         let headers: Headers = new Headers();
         headers.append("authorization", "Basic " + btoa(username + ":" + password)); 
         headers.append("Content-Type", "application/json");
         let options = new RequestOptions({ headers: headers, withCredentials: true });

         return this._http.get(this._productUrl,options)

            .map((response: Response) => <IProduct[]> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);

    }
     private handleError(error: Response) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

1 个答案:

答案 0 :(得分:0)

你可以试试这个

private _productUrl = 'http://localhost:8092/openmrs-standalone/ws/rest/v1/session';

getProducts(): Observable<any> {
   let username: string = 'admin';
   let password: string = 'Admin123';
   let headerOptions = {
      'Accept': `application/json`,
      'Access-Control-Allow-Credentials': 'true',
      'Authorization': 'Basic ' + btoa(username + ":" + password)
   };
   let headers = new Headers(headerOptions );
   return new RequestOptions({ headers: headers });
}