tengo una api rest que pruebo desde el postman y obtengo respuesta sin problemas.
"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,
Esta petición tiene como cabecera un token como parte de la autenticación que tiene implementada. Ahora desde mi app angular consumo el token a la hora de el logeo y no tiene problemas , funciona bien , el problema está cuando intento obtener la lista de los usuarios que debe devolver el json que mostré anteriormente.
Este es el código en angular
Este es el servicio
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);
}
}
Este es el 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);
});
}
y este es el 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>
Necesito poder consumir el servicio y mostrar la lista de usuarios visualmente porque cuando entro en el navegador y cargo la pagina no me muestra nada y en la consola se me imprime el siguiente error.
zone.js:2935 OPTIONS http://localhost:8080/pineapple-admin-core/users/list 401 (No Autorizado) usercrud:1 Failed to load http://localhost:8080/pineapple-admin-core/users/list: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.
Muchas gracias por su ayuda de antemano