gpt4 book ai didi

javascript - 无法将 Observable 转换为 Object[]

转载 作者:行者123 更新时间:2023-12-03 00:08:54 28 4
gpt4 key购买 nike

我想从我的 JSON 服务器获取用户数据,这是它的数据:

{

"users": [
{
"id": 1,
"username": "test",
"password": "test",
"role": "admin",
"token":"yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw"
}
]
}

为此,我使用了 get 请求,这是我的代码:

@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>)并且可以没有收到用户数组,我应该更改什么来解析对 User[] 数组的请求响应?

最佳答案

在你的主要组件中,你将使用你需要订阅的数据作为它的可观察对象。所以请尝试以下操作。

public users = [];

this.exampleService.getUsers().subscribe(data => {
console.log(data); // should be your users.
this.users = data.users;
}, error => {
console.log(error); // if api returns and error you will get it here
});

您的编辑

我仍然会坚持使用 Observable,但这取决于偏好。只要this.authService.getUsers()返回 Observable<IUsers>这应该可以正常工作。还建议创建一个接口(interface)来处理数据。

export interface IUsers
{
id: number;
username: string;
password: string;
role: string;
token: string;
}


public users: IUsers[] = [];

public ngOnInit(): void {

this.authService.getUsers().subscribe(data => {
console.log(data); // should be your users.
this.users = data.users;

}, error => {
console.log(error); // if api returns and error you will get it here
});

});
}

这应该给你 this.users 以便在拦截器中使用。如果这没有帮助,请添加代码 this.authService.getUsers()希望对您有所帮助,如果您遇到任何问题,请发表评论。

关于javascript - 无法将 Observable 转换为 Object[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54841032/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com