const cudOptions = {headers: new HttpHeaders({'Content-Type': 'application/json'})}
@Injectable()
export class UserServiceService {
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);
}
getUserMe(){
return this.http.get(this.getMe).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);
}
}
And this is the component
@Component({
selector: 'app-user-crud',
templateUrl: './user-crud.component.html',
styleUrls: ['./user-crud.component.css']
})
export class UserCrudComponent implements OnInit {
me : any;
user: User;
constructor(private router: Router, private userService: UserServiceService) { }
ngOnInit() {
this.userService.getUserMe().subscribe((data : any) => {
console.log(data);
this.me = data;
})
}
/*
result => {
if (result.code != 200)
console.log(result);
else
this.users = result.data;
},error => {
console.log(<any>error);
}
*/
getUsers() {
this.userService.getUsers().subscribe((data : any) => {
console.log(data.content);
},(err : HttpErrorResponse)=>{
console.log(err);
});
}
}
And when I send the request for to authenticate , that resturn success , and when i invoke the service getMe(), return 401.
I saw the request in mozilla and return 401 error , but if i edit and resend the petition adding 'Auhorization':'Bearer'+token , return
200 OK, but this work is the interceptor , and i wrote that code , like in the documentation, please , HELP. Thank you very mutch and
sorry for my English.