如何检查属性是否有字符串?

时间:2016-01-06 21:38:14

标签: javascript angularjs

如果响应有一个字符串,如果响应有一个字符串,如果响应有一个字符串然后执行if条件,如何检查服务器的错误我希望使$scope.ActiveFile为真。

main.js

  $scope.onError = function(e) {
        console.log('Error while uploading attachment', e.XMLHttpRequest.response);

        $scope.errorMessage = JSON.parse(e.XMLHttpRequest.response).techErrorMsg;
        if ($scope.errorMessage >= 1){
        $scope.applyActiveFile = true;
        }
    };

response.json

Server response: {"errorCode":500,"errorMsg":"Service failed. Please contact administrator.","techErrorMsg":"Sheet : PROCESS_INVENTORY not found in the File"}

3 个答案:

答案 0 :(得分:1)

要解决您的特定查询,这应该有效

if ($scope.errorMessage != null/blank) //whatever suits you
{
  $scope.applyActiveFile = true;
}

现在回答你的问题标题 - 检查属性是否为字符串

if (typeof response === string)
/*typeof tells the type of operator, it will return number in case of number and  string in case of string*/
{
  $scope.applyActiveFile = true;
}

答案 1 :(得分:1)

像这样的东西

  for (var i in $scope.errorMessages){
     if (typeof $scope.errorMessages[i] === "string"){
            alert($scope.errorMessages[i]);
     }
 }

在浏览器控制台输入中测试:

var a = {"errorCode":500,"errorMsg":"Service failed. Please contact administrator.","techErrorMsg":"Sheet : PROCESS_INVENTORY not found in the File","thirdFieldNotString":1};
  for (var i in a){
     if (typeof a[i] === "string"){
        alert('Value is string');                
     }
  };

答案 2 :(得分:1)

正如mic4ael所说,你可以使用一些条件,如:

if ($scope.errorMessage)
    $scope.applyActiveFile = true;

您可以使用一些正则表达式,例如:

if ((/^\s*$/).test($scope.errorMessage))
    $scope.applyActiveFile = false;

...它会检查字符串是否为空或只有空格并将触发器设置为false。你只想用这个来检查一个或两个值,但是否则会导致性能不佳。

许多其他解决方案......