aurelia-fetch-client和配置

时间:2016-09-06 08:48:12

标签: typescript fetch aurelia aurelia-fetch-client

我使用Aurelia的fetch客户端从REST服务中获取数据。 我的问题是,即使HttpClient仅在AuthService类中导入一次,我必须在每个请求之前将配置对象传递给它,否则它将回退到默认值。

似乎我的拦截器没有脱落,我只需配置一次。 但我的baseurl往往会脱落。奇怪的是,当baseurl停止工作时,我遇到了隔离问题。有时确实如此,有时却没有。

这是我的auth.service.ts

import { APP_CONSTANTS } from '../app.constants';

import { Aurelia } from 'aurelia-framework';
import { HttpClient, json } from 'aurelia-fetch-client';
import { inject } from 'aurelia-framework';

@inject(HttpClient, Aurelia)
export class AuthService {

    isRequesting: boolean = false;
    isAuthenticated: boolean = false;
    company: any;
    user: any;
    token: string;
    httpConfig: any;

    constructor(private http: HttpClient, private app: Aurelia) {
        let self = this;
        this.httpConfig = config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL);
        }
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withInterceptor({
                    request(request) {
                        self.isRequesting = true;
                        return request;
                    },
                    response(response) {
                        if(response.status === 401) {
                            self.logout();
                        }
                        self.isRequesting = false;
                        return response;
                    }
                })
        });
        let token = window.localStorage.getItem('ol_token');
        let companyName = window.location.pathname;
        companyName = companyName.replace('/', '');
        if(!companyName.length) {
            this.getCompany('onlinelog')
                .then(response => response.json())
                .then(result => {
                    self.company = result.data;
                })
        } else {
            this.getCompany(companyName)
                .then(response => response.json())
                .then(result => {
                    self.company = result.data;
                });
        }
        if(token) {
            this.token = token;
            this.http.configure(config => {
                config.withDefaults({
                    headers: {
                        'Authorization': token,
                    }
                })
            })
            this.getUserCredentials()
                .then(response => response.json())
                .then(result => {
                    self.user = result.data;
                })
            this.isAuthenticated = true;
        }
    }

    getCompany(name) {
        this.http.configure(this.httpConfig);
        return this.http.fetch(`company/info/${name}`);
    }

    loadingTest() {
        let self = this;
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': this.token
                    }
                })
        });
        this.http.fetch('isauthed')
            .then(response => response.json())
            .then(result => {
                console.log(result);
            })
    }

    getUserCredentials() {
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': this.token
                    }
                })
        });
        return this.http.fetch(`isauthed`);
    }

    authenticate(user, password) {
        let obj = {
            login: user,
            password: password
        }
        this.http.fetch(`authenticate`, {
            method: 'post',
            body: json(obj)
        }).then(response => response.json())
        .then(result => {
            this.user = result.data;
            this.token = result.token;
            this.setToken(result.token);
            window.localStorage.setItem('ol_token', result.token);
            this.app.setRoot('app');
        })
    }

    setToken(token) {
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': token
                    }
                })
        })
    }

    logout() {
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': null
                    }
                })
        });
        this.token = '';
        window.localStorage.removeItem('ol_token');
        this.user = null;
        this.app.setRoot('auth/auth');
    }

}

如您所见,“authenticate”方法不需要重新配置baseurl。但是,如果我尝试在不重新配置的情况下调用getUserCredentials方法,则会出现JSON解析错误,因为它尝试将请求发送到“localhost:9000 / isauthed /”而不是“localhost:4000 / api / isauthed /”,就像它应该。

任何帮助将不胜感激!

我希望它工作的方式是,我使用baseUrl和拦截器ONCE配置HttpClient,并且能够根据用户是否经过身份验证动态编辑发送的标头配置。

0 个答案:

没有答案