I am currently facing an issue with calling a service in my Angular 2 project. The service works fine in DHC, but when I try to implement it in my project, it crashes. The method requires a POST request and expects an object containing an email and password in the body. The response from the service is a token that will be used for authorization throughout the project.
Below is the code snippet:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class LoginService {
constructor(private http: Http) {
}
getToken(){
var baseUrl = "xxx.xxx.x.xxx:xxxx/project/v1/admin/login";
var headers = new Headers();
headers.append("Content-Type", 'application/json');
var options = new RequestOptions({ headers: headers });
var object = {'email': 'xxxxxx', 'pass':'xxxx' }
var body = JSON.stringify(object);
return this.http
.post(baseUrl, body, options)
.map((response: Response) => response.json())
.subscribe(
data => console.log('Success uploading the opinion '+ data, data),
error => console.error(`Error: ${error}`)
);
}
}
I have also tried implementing XMLHttp Request call in Angular 2, but encountered the same error. I am unsure if it is supported in Angular 2. Here is the method:
return Observable.fromPromise(new Promise((resolve, reject) => {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", baseUrl, true);
xhr.send(body);
}));