Angular2 处理 http 响应 [英] Angular2 handling http response

查看:33
本文介绍了Angular2 处理 http 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是有一个关于在服务中构建和处理来自 http 请求的响应的问题.我正在使用 Angular2.alpha46 Typescript(刚开始测试它 - 我喜欢它...... Ps.. 感谢所有一直致力于它并通过 github 做出贡献的人)

I just have a question regarding structuring and handling responses from http requests within a service. I am using Angular2.alpha46 Typescript ( Just started testing it out- which I love... Ps.. Thank you all the people who have been working on it and contributing via github )

所以采取以下措施:

login-form.component.ts

import {Component, CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2';
import {UserService} from '../../shared/service/user.service';
import {Router} from 'angular2/router';
import {User} from '../../model/user.model';
import {APP_ROUTES, Routes} from '../../core/route.config';

@Component({
    selector: 'login-form',
    templateUrl: 'app/login/components/login-form.component.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})

export class LoginFormComponent {
    user: User;
    submitted: Boolean = false;

    constructor(private userService:UserService, private router: Router) {
        this.user = new User();
    }

    onLogin() {
        this.submitted = true;

        this.userService.login(this.user,
            () => this.router.navigate([Routes.home.as]))
    }
}

从这个组件我导入我的 userService 它将容纳我登录用户的 http 请求,服务看起来像这样:

from this component I import my userService which will house my http request to login the user the service looks like this:

user.service.ts

import {Inject} from 'angular2/angular2';
import {Http, HTTP_BINDINGS, Headers} from 'angular2/http';
import {ROUTER_BINDINGS} from 'angular2/router';
import {User} from '../../model/user.model';

export class UserService {

    private headers: Headers;

    constructor(@Inject(Http) private http:Http) {
    }

    login(user: User, done: Function) {
        var postData = "email=" + user.email + "&password=" + user.password;

        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/x-www-form-urlencoded');

        this.http.post('/auth/local', postData, {
                headers: this.headers
            })
            .map((res:any) => res.json())
            .subscribe(
                data => this.saveJwt(data.id_token),
                err => this.logError(err),
                () => done()
            );
    }

    saveJwt(jwt: string) {
        if(jwt) localStorage.setItem('id_token', jwt)
    }

    logError(err: any) {
        console.log(err);
    }
}

我想要做的是能够处理调用在http请求之后返回的响应.例如,如果用户凭据无效,我会从后端传回 401 响应.我的问题是处理响应并将结果返回到我从中调用方法的组件的最佳方法是哪里,以便我可以操纵视图以显示成功消息或显示错误消息.

What I want to do is to be able to handle the response the call returns after the http request. For instance if the user credentials are invalid I pass a 401 response back from the backend. My question is where is the best way to handle the response and return the result back to the component where i called the method from so I can manipulate the view to show either the success message or display an error message.

在我登录的服务中,我目前没有处理响应,我只是简单地回调到原始组件,但我觉得这不是正确的方法吗?有人可以解释一下在这种典型情况下他们会做什么吗?我会在订阅函数的第一个参数中处理响应吗:

At the moment in my service under login I am currently not handling the response I am simply doing a callback back to the original component but I feel this isnt the correct way to go about it? Can someone shed some light on what they would do in this typical scenario? Would I handle the response in the first parameter of the subscribe function like:

 login(user: User, done: Function) {
     var postData = "email=" + user.email + "&password=" + user.password;

    this.headers = new Headers();
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');

    this.http.post('/auth/local', postData, {
            headers: this.headers
        })
        .map((res:any) => res.json())
        .subscribe(
            (data) => {
                // Handle response here
                let responseStat = this.handleResponse(data.header)

                // Do some stuff
                this.saveJwt(data.id_token);

                // do call back to original component and pass the response status
                done(responseStat);
            },
            err => this.logError(err)
        );
}

handleResponse(header) {
    if(header.status != 401) {
        return 'success'
    } 

    return 'error blah blah'
}

在这种情况下回调是否合适,或者是否可以通过 observable 或 promise 更好地处理?

Is a call back fine in this case or can this be handled better with an observable or a promise?

总结我要问的是......处理来自http响应的响应并处理来自user.service.ts返回的表单视图中的状态的最佳实践是什么到 login-form.component.ts

Concluding what I am asking is... What is the best practice to handle the response from the http response and handle the status in the view of the form from the user.service.ts back to the login-form.component.ts

推荐答案

更新 alpha 47

从 alpha 47 开始,不再需要以下答案(对于 alpha46 及以下).现在 Http 模块会自动处理返回的错误.所以现在很简单,如下

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 及以下

你可以在 map(...) 中处理响应,在 subscribe 之前.

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

这是一个带有简单示例的 plnkr.

Here's a plnkr with a simple example.

请注意,在下一个版本中,这不是必需的,因为所有低于 200 和高于 299 的状态代码都会自动抛出错误,因此您不必自己检查它们.查看此提交了解更多信息.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

这篇关于Angular2 处理 http 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆