简体   繁体   中英

JSON.parse won't convert JSON string into object in Angular

I'm building a role based login for an angular app and when you first enter your credentials a session object is sent back with a bunch of properties, including an array of roles the user can select to sign in as. When the user selects the radio button for the corresponding role they want to be signed in as, eg "Administrator", I use ng-model' to update $scope.model.selected` to whatever object they chose.

However, at some point in the UI $scope.model gets parsed into a string when I need it to be a javascript object. In short, I'm trying to convert my model back to an object and I can't get JSON.parse($scope.model) to work.

Here's my controller:

$scope.submit = function() {
      $http
        .post(app.api.root + 'session-tokens', $scope.user)
        .then(
          // SUCCESS
          function (response) {
            $scope.model = { selected: response.data.results.roles[0] };
            $scope.results = response.data.results;
            $scope.isCorrect = true;
            $scope.welcome = 'Welcome, ' + $scope.user.username + '!';

            // redirect after login -- need to change this to a profile page
            // $location.path('/patients/22');
            $scope.login = function() {
              $scope.model = JSON.parse($scope.model);
              authSvc.user({
                id: response.data.results.userId,
                token: $scope.model.selected.token,
                role: $scope.model.selected.roleName,
                providerName: $scope.model.selected.providerName,
                username: $scope.user.username,
                isAuthenticated: true
              });
              $scope.user = authSvc.user();
              console.log(typeof $scope.model.selected);
            };
          }
};

The function that I want to do the conversion is $scope.login() , which fires after the user selects a role and clicks login.

Any idea how I can get this to work? And I don't think I'm on a new enough version of angular to use angular.fromJson .

Thanks.

EDIT

Here's the error I get in the console:

SyntaxError: Unexpected token o
at Object.parse (native)
at Scope.$scope.login (eval at <anonymous> (http://localhost:4000/$js/jquery.js:336:5), <anonymous>:32:39)
at http://localhost:4000/$js/angular.js:10288:21
at http://localhost:4000/$js/angular.js:18086:17
at Scope.$eval (http://localhost:4000/$js/angular.js:12045:28)
at Scope.$apply (http://localhost:4000/$js/angular.js:12145:23)
at Scope.$delegate.__proto__.$apply (<anonymous>:855:30)
at HTMLFormElement.<anonymous> (http://localhost:4000/$js/angular.js:18085:21)
at HTMLFormElement.jQuery.event.dispatch (http://localhost:4000/$js/jquery.js:4371:9)
at HTMLFormElement.elemData.handle (http://localhost:4000/$js/jquery.js:4057:28) 

EDIT

So $scope.model does actually return an object, but $scope.model.selected returns a json string, and I need it to be an object.

The string returned is:

{"roleName":"Group Provider","providerId":100,"providerName":"TestProvider","token":"XXX"}

CONSOLE.LOGS

console.log(response.data.results):
Object {userId: 3, roles: Array[2]}

console.log(response.data.results.roles[0]):
Object {roleName: "Administrator", providerId: 2, providerName: "TestLastNAme, Test", token: "xxx", $$hashKey: "0fL"}

console.log($scope.model):
Object {selected: "{"roleName":"Group Provider","providerId…Nn0.lwB6AggcMkvH_LcQzpUdLlbk3XBHTGBqCd8K07HBIfo"}"}

console.log($scope.model.selected):
{"roleName":"Group Provider","providerId":237,"providerName":"TestProvider","token":"xxx"} 

console.dir($scope.model):
Object
    selected: "{"roleName":"Insurance Group Provider","providerId":237,"providerName":"TestProvider","token":"xxx"}"
    __proto__: Object

当您尝试在对象上使用JSON.parse()时,将发生该错误。

All of that and it turns out the problem was I was using value="{{model}}" on the radio buttons instead of angular's ng-value="model" . value= will parse the object into a string while ng-value will keep it as an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM