首页 文章

使用Angular 2/4将json发布到API

提问于
浏览
1

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

enter image description here

在作为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});
}

我的第一个问题是: Is this the correct way to pass the json object and call this 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)
    );
}

我的第二个问题是: How should I check whether a token is returned back or an error?

1 回答

  • 1

    问题1:

    在角度中执行 http.post() 时,不需要对主体对象进行字符串化 . 只需使用普通对象即可, 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 对象中 . 如果出现错误,则不应收到任何令牌,您应该在错误回调时处理错误 .

相关问题