我不得不不久前處理同樣的問題,並用以下解決方案上來。我不知道這是否是最佳做法,並且非常喜歡Angular 1的攔截器作爲此解決方案,但這適用於我:
我爲內置的Http
服務創建了包裝服務。當我想使用Http
時,我改爲注入此服務。
@Injectable()
export class HttpWrapper {
constructor(private loginService:LoginService, private http:Http, private router:Router) {
}
get(url: string, options?: RequestOptionsArgs): Promise<Response> {
let promise: Promise<Response> = this.http.get(url, this.addHeaders(options)).toPromise();
return new Promise((resolve, reject) => {
promise.then(success => {
resolve(success);
}, error => {
this.onError(error);
reject(error);
});
});
}
//... repeat the same concept for post, put, delete...
private addHeaders(otherOptions?: RequestOptionsArgs): RequestOptions {
let headers = new Headers({'Content-Type': 'application/json', token: this.loginService.token});
let options = new RequestOptions({ headers: headers });
if (otherOptions) {
options.merge(otherOptions);
}
return options;
}
private onError(reason) {
if(reason.status === 401) {
this.router.navigateByUrl(`/login?${encodeURIComponent(this.router.lastNavigationAttempt)}`);
}
}
}
*請注意,我使用的是不推薦使用的路由器。我正在等待Angular團隊正確記錄新的文件。
我覺得這幾乎可以解答你的問題1-3。至於獎金問題,更多的是用例問題。如果你知道你會在任何情況下使用用戶的數據,那麼預先加載用戶的數據是有道理的。否則,爲了不在開始時使應用程序權限過載,只能在需要時加載這些數據。