【问题标题】:POSTing json to API with Angular 2/4使用 Angular 2/4 将 json 发布到 API
【发布时间】:2017-07-10 23:15:56
【问题描述】:

我是 Angular 4 和 REST API 开发的新手。我在后端开发了一个登录 API,当我使用 Postman 调用它时它工作正常:

在 Angular 4 项目的前端应用程序中,我创建了一个服务来调用这个登录 API。这是我在此服务中创建的方法:

sendCredential(username: string, password: string) {
    const url = 'http://localhost:8080/authenticate/user';
    const body = '{"username": "' + username + '", "password": "' + password + '"}';
    const headers = new Headers(
        {
            'Content-Type': 'application/json'
        });
    return this.http.post(url, body, {headers: headers});
}

我的第一个问题是: 这是传递 json 对象并调用此 API 的正确方法吗?

我还创建了一个调用服务中的方法的组件。这是我在这个组件中创建的方法/事件处理程序:

onSubmit(uname: string, pwd: string) {
    this.loginService.sendCredential(uname, pwd).subscribe(
        res => {
            this.loggedIn = true;
            localStorage.setItem('PortalAdminHasLoggedIn', 'true');
            location.reload();
        },
        err => console.log(err)
    );
}

我的第二个问题是: 我应该如何检查令牌是否被退回或错误?

【问题讨论】:

    标签: json angular rest api


    【解决方案1】:

    问题一:

    当您在 Angular 中执行 http.post() 时,您不需要对 body 对象进行字符串化。只需使用普通对象即可,Http 类将帮助您在内部解析它:

    sendCredential(username: string, password: string) {
        const url = 'http://localhost:8080/authenticate/user';
        //do not need to stringify your body
        const body = {
            username, password
        }
        const headers = new Headers(
            {
                'Content-Type': 'application/json'
            });
        return this.http.post(url, body, {headers: headers});
    }
    

    问题2:

    至于您的错误,请注意 Angular 也会捕获每个 http 错误。并且通过http错误,这意味着任何<200>=300的状态代码都将是一个错误。因此,只有介于 200 和 300 之间的状态代码被认为是成功的。收到错误后,angular 将抛出 Observable 错误,您需要明确处理(您正确地处理了该错误):

    onSubmit(uname: string, pwd: string) {
        this.loginService.sendCredential(uname, pwd).subscribe(
            res => {
                //token should be in your res object
                this.loggedIn = true;
                localStorage.setItem('PortalAdminHasLoggedIn', 'true');
                location.reload();
            },
            err => {
                //handle your error here.
                //there shouldn't be any token here
                console.log(error);
            }
        );
    }
    

    使用上面的代码,您应该会在成功的回调中收到您的令牌,它将位于 res 对象中。如果有错误,则不应收到任何令牌,您应该在错误回调中处理错误。

    【讨论】:

    • 我只是得到“类型 { headers: headers } 的参数不可分配给 RequestOptionArgs | undefined 类型的参数”等。
    • 我现在导入了标头,但是得到了 NodeInvocationException: Uncaught (in promise): ReferenceError: Headers is not defined ReferenceError: Headers is not defined
    • 即 import { Headers } from '@angular/http
    猜你喜欢
    • 2021-02-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2017-01-19
    • 1970-01-01
    • 2013-05-30
    相关资源
    最近更新 更多