如何在角度2中加载组件时加载app.config.ts文件

时间:2017-07-23 11:59:02

标签: angular angular2-routing angular2-template angular2-services

当我登录时,我在localstorage中设置登录详细信息和令牌,然后重定向到员工组件。在我的API中,我需要发送令牌。我在一个公共文件调用应用程序中放置标题并附加令牌.config.ts。

这里发生的事情是..当我登录时,下一页是获取员工列表。这个令牌从app.config.ts变为空,所以我的API显示错误{'token not provide'}。我刷新了我的页面,然后它的罚款。这对我来说很烦人,因为很久以后任何人都可以建议我帮忙。或者我是否需要抽出时间来调用我的API? 我有app.config.ts文件,

@Injectable()
export class AppConfig { 
    config: any;
    serverUrl: any;
    loginToken: any;
    token: any;
    imageUrl: any;
    headers: any;
    constructor(public router: Router) {
        this.headers = new Headers();
        this.loginToken = localStorage.getItem('EmployeeToken');
        this.token = "Bearer" +' '+ this.loginToken;
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Authorization', this.token);
   }
}

我在hireye.component.ts,

中使用它
 import { Component} from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { AppConfig } from "../../app.config";

@Component({
    templateUrl: './employee.component.html',
    providers: [AppConfig]
})

export class EmployeeComponent {
    constructor(public _appConfig: AppConfig) {
        this.http = http;
        this.serverUrl = _appConfig.serverUrl;
        this.headers = _appConfig.headers;
        this.getAllEmployees();
    }

    // Get Employees
    getAllEmployees() {
        this.http.get(this.serverUrl + 'employees', { headers: this.headers })
            .subscribe(response => {
                if (response && response.json()) {
                       ////
                    }
                } else {
                    this.employees = [];
                }
            })
    }
}

0 个答案:

没有答案