【发布时间】:2019-02-23 11:21:20
【问题描述】:
我想从我的 JSON 服务器获取 用户 数据,这是数据:
{
"users": [
{
"id": 1,
"username": "test",
"password": "test",
"role": "admin",
"token":"yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw"
}
]
}
为此我使用了获取请求,这是我的代码:
@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor,OnInit {
constructor(private authService: AuthService, private userData: Http) { }
private endpoint: string = 'http://localhost:3000/users';
users: Array<any> = [];
ngOnInit(){
this.authService.getUsers()
.toPromise()
.then((users: Array<User>) => {
this.users = users;
return users;
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// const users: User[] = [
// { id: 1, username: 'test', password: 'test', role: "user" }
// ];
const authHeader = request.headers.get('Authorization');
const isLoggedIn = authHeader && authHeader.startsWith('Bearer fake-jwt-token');
// wrap in delayed observable to simulate server api call
return of(null).pipe(mergeMap(() => {
// authenticate - public
if (request.url.endsWith('3000/users') && request.method === 'PUT') {
console.log(this.users);
const user = this.users.find(x => x.username === request.body.username && x.password === request.body.password);
if (!user) return error('Username or password is incorrect');
return ok({
id: user.id,
username: user.username,
role: user.role,
token: user.token
});
}
// get all users
if (request.url.endsWith('/users') && request.method === 'GET') {
if (!isLoggedIn) return unauthorised();
return ok(this.users);
}
// pass through any requests not handled above
return next.handle(request);
}))
.pipe(materialize())
.pipe(delay(500))
.pipe(dematerialize());
// private helper functions
function ok(body) {
return of(new HttpResponse({ status: 200, body }));
}
function unauthorised() {
return throwError({ status: 401, error: { message: 'Unauthorised' } });
}
function error(message) {
return throwError({ status: 400, error: { message } });
}
}
}
export let fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendInterceptor,
multi: true
};
我已经改变了我的逻辑并尝试使用 Promises 而不是 Observable,但在这种情况下我得到了一个空数组(似乎我无法将收到的响应解析为 User [],而是我得到了 Promise>)并且可以'没有收到用户数组,我应该改变什么来解析对用户[]数组的获取请求响应?
【问题讨论】:
标签: javascript json angular rxjs