无法将可观察到的对象转换为对象[]

时间:2019-02-23 11:21:21

标签: javascript json angular

我想从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 []数组的获取请求响应?

1 个答案:

答案 0 :(得分:1)

在要使用数据的主组件中,需要将其作为Observable进行订阅。因此,请尝试以下操作。

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>,就可以正常工作。还建议创建一个接口来处理数据。

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()添加代码 希望对您有所帮助,如果遇到任何问题,请发表评论。