Angular2 watch 302 redirection while retrieving resources

I have a requirement to pull a few resources from another domain that belongs to my company. I want to get protected HTML content using GET requests.

When the user exits the application, the requested content will return 302 to the login page.

My attempts to sniff the headlines for 302 did not return what I had hoped so far. The response returned by my Observable is 200 (login page).

Here is my sample application.

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?

+5
source share
2 answers

If the server sends a redirect with a status code of 302 with the URL for redirection in the Location header, the redirect is automatically processed by the browser, i.e. a request is being made to this URL.

This is why XHR (and the wrapper around Angular2, i.e. the Http class) will not see the result of the first request, but only the answer of the second.

+11
source

This is my working code to redirect 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 || {}; } 
0
source

All Articles