Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
879 views
in Technique[技术] by (71.8m points)

angular - Angular2 watch for 302 redirect when fetching resource

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...