I have an api rest that I try from the postman and I get an answer without problems.
"content": [
{
"username": "john.doe",
"password": "$2a$10$l1uYkX5AX3pul86A3O5mgujwff6dYDCepixCGwyMjslWP3frCoSpi",
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]",
"phone": "+53582424",
"address": "",
"active": true,
"fullName": "JohnDoe",
"blocked": false
},
{
"username": "admin.admin",
"password": "$2a$10$l1uYkX5AX3pul86A3O5mgujwff6dYDCepixCGwyMjslWP3frCoSpi",
"firstName": "Admin",
"lastName": "Admin",
"email": "[email protected]",
"phone": "+53582424",
"address": "",
"active": true,
"fullName": "AdminAdmin",
"blocked": false
}
],
"last": true,
"totalElements": 2,
This request has as a header a token as part of the authentication it has implemented. Now from my angular app I consume the token at the time of the login and it has no problems, it works fine, the problem is when I try to get the list of users that must return the json that I showed before.
This is the code in angular
This is the service
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders}from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import { User } from '../model/user';
import {HttpModule, Http, Response}from '@angular/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
const cudOptions = {headers: new HttpHeaders({'Content-Type': 'application/json'})}
@Injectable()
export class UserServiceService {
private usersUrl: string = 'http://localhost:8080/pineapple-admin-core/users/list';
private userUrl: string = 'http://localhost:8080/pineapple-admin-core/users/get';
private userAdd: string = 'http://localhost:8080/pineapple-admin-core/users/add';
private userDelete: string = 'http://localhost:8080/pineapple-admin-core/users/delete';
private userUpdate: string = 'http://localhost:8080/pineapple-admin-core/users/update';
private loginUrl = "http://localhost:8080/pineapple-admin-core/oauth/token";
constructor(private http: HttpClient) {
}
getUsers(): Observable<User>{
return this.http.get<User>(this.usersUrl, {headers : new HttpHeaders({'Authorization' : 'Bearer '+localStorage.getItem('userToken')})})
.catch(this.handleError);
}
getUser(id: string|number): Observable<User>{
const url = '${this.userUrl}/${id}';
return this.http.get<User>(this.userUrl).catch(this.handleError);
}
addUser(user: User): Observable<User>{
const newUser = Object.assign({}, user);
return this.http.post<User>(this.userAdd, newUser, cudOptions)
.catch(this.handleError);
}
deleteUser(user: User|number){
const id = typeof user === 'number' ? user : user.id;
const url = '${this.userDelete}/${id}';
return this.http.delete(url,cudOptions)
.catch(this.handleError);
}
updateUser(user : User): Observable<User>{
return this.http.put(this.userUpdate, user, cudOptions)
.catch(this.handleError);
}
userAuthentication(userName: string, password: string){
var data = "grant_type=password&username="+userName+"&password="+password;
let headers : HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers = headers.append('Authorization', 'Basic b25lbW9yZWNsaWVudGlkOlhZN2ttem9OemwxMDA=');
return this.http.post(this.loginUrl, data, {headers: headers}).catch(this.handleError);
}
private handleError(error: any){
console.error(error);
return Observable.throw(error);
}
}
This is the component.ts
import { Component, OnInit } from '@angular/core';
import { User } from '../../model/user';
import { Router } from '@angular/router';
import { UserServiceService } from '../../services/user-service.service';
import { Observable } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
selector: 'app-user-crud',
templateUrl: './user-crud.component.html',
styleUrls: ['./user-crud.component.css']
})
export class UserCrudComponent implements OnInit {
private users: any[];
constructor(private router: Router, private userService: UserServiceService) { }
ngOnInit() {
this.getUsers();
}
getUsers() {
this.userService.getUsers().subscribe((data : any) => {
console.log(data.content);
},(err : HttpErrorResponse)=>{
console.log(err);
});
}
and this is the html
<table>
<thead>
<tr>
<td>Columna 1</td>
<td>Columna 2</td>
<td>Columna 3</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of users">
<td>{{ item.id }}</td>
<td>{{ item.lastname }}</td>
<td>{{ item.firstname }}</td>
</tr>
</tbody>
I need to be able to consume the service and display the list of users visually because when I enter the browser and load the page it does not show me anything and in the console I get the following error.
zone.js: 2935 OPTIONS link 401 (Unauthorized) usercrud: 1 Failed to load link : Response to preflight request does not pass access control check: No ' Access-Control-Allow-Origin 'header is present on the requested resource. Origin ' link ' is therefore not allowed access. The response had HTTP status code 401.
Thank you very much for your help in advance