【问题标题】:Cant Convert Observable to Object[]无法将 Observable 转换为 Object[]
【发布时间】: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


    【解决方案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&lt;IUsers&gt;,这应该可以正常工作。还建议制作一个接口来处理数据。

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

    【讨论】:

    • 嘿,谢谢你的回复,我认为我不应该使用订阅,所以我改变了我的逻辑,但现在我有一个新问题,我想我无法解析我对此的回复数组用户 [],您知道我应该如何更改我的逻辑/代码以获得正常响应吗?
    • 添加了一个编辑希望对您有所帮助,您能否为我确认一下,因为我不确定我的头顶,在拦截器启动之前订阅中的数据的 console.log() 是否会触发。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多