Angular2 watch for 302 redirect when fetching resource

人盡茶涼 提交于 2019-11-26 17:23:50

问题


I have a requirement to pull a few resources from another domain held by my company. I want to pull secured HTML content with GET requests.

When a user is signed out of the application the requested content will return a 302 to the login page.

My attempts to sniff the headers for a 302 haven't returned what I'd hoped for so far. The response returned by my Observable is a 200 (login page).

Here is my sample app.

export class MenuComponent implements OnInit {

    private _resourceUrl = "http://localhost:3001/resources/menu";

    constructor(private _http: Http){
    }

    menu: string;

    ngOnInit(): void {
        this.getMenu()
            .subscribe(
                response => {
                    console.log(`Response status: ${response.status}`);

                    this.menu = response.text();
                },
                error => console.log(<any>error));
    }

    getMenu(): Observable<Response>{        
        return this._http.get(this._resourceUrl)
            .map((response: Response) => response)
            .catch(this.handleError);
    }

    private handleError(error: Response){
        console.log(error);
        return Observable.throw(error.json().error || 'Server Error');
    }
}

Am I even on the right track?


回答1:


If the server sends a redirect with a 302 status code with the URL to redirect within a Location header, the redirect is automatically handled by the browser, i.e. a request to this URL is executed.

That's why XHR (and the Angular2 wrapper around it, i.e. the Http class) won't see the result of the first request but only the response of the second one.




回答2:


This is my working code for redirecting to ServiceData. Angular2(4) and ASP net Core.

private post(url: string, data?: any) {
    return this.http.post(url, data, { headers: this.headers })
      .map(response => this.extractData(response, true));
}

private extractData(res: Response, mapJson = true) {
    let body: any = res;
    // redirect
    if (body.url.search('ReturnUrl') != -1) {
        let url = new URL(body.url);

        // get patch redirect simple /account/login
        let pathname = url.pathname;

        // get params redirect simple ?ReturnUrl=%2Fapi%2Fitems%2FGetitems
        let search = url.search;

        // 1 navigate with params
        this.router.navigate.navigate([pathname], { queryParams: { returnUrl: search } });

        // OR ...

        // 2 navigate only pathname
        this.router.navigate.navigate([pathname]);
        return {};
    }            

    if (mapJson) {
        body = body.json();
    }
    return body || {};
}


来源:https://stackoverflow.com/questions/36885556/angular2-watch-for-302-redirect-when-fetching-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!