如何在Angularjs 2.0中使用基本身份验证调用REST服务?

时间:2015-07-28 08:31:23

标签: angular basic-authentication

我在Angularjs 1.3中有java REST服务和使用者。服务是基于JSON的,并且期望BASIC身份验证(用户名密码)。 在AgJs 1.3中,我使用Base64工厂代码(在谷歌上找到)从用户名和密码创建基本身份验证令牌,并能够成功使用服务。

我在AgJs 2.0文档中读取了HTTP类,但我没有找到有关基本身份验证的任何信息。

有人可以提供示例代码以使用BASIC身份验证在Angularjs 2.0中使用REST服务吗?

提前致谢!

最诚挚的问候!

我的AgJs 1.3代码:

var url =" http://x.x.x.x:xxxx/data/" +数字;

$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('username' + ':' + 'password');
$http.defaults.headers.common['Content-Type'] = 'application/json';

$http({ method: 'GET', url: url }).
        success(function (data, status, headers, config) {
           alert(data);
        }).
        error(function (data, status, headers, config) {
            alert("error: " + data);
        });

2 个答案:

答案 0 :(得分:1)

我刚从angular2发帖到具有Basic身份验证的服务器,这可行:

    chartarea.CursorY.AxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary;

希望这能回答你的问题。

答案 1 :(得分:0)

取决于您是否正在使用新的Angular2 http api,或者像fetch这样的外部内容。

如果后者你可以做这样的事情,只记得用zone包装:

myHeaders = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + Base64.encode('username' + ':' + 'password')
    }
return Zone.bindPromiseFn(fetch)(
            url,
            {
                method: 'GET',
                headers: myHeaders,
                body: JSON.stringify(myData)
            }).then(
                r => {return r.json()}
        );