2017-03-20 8 views
0

Nodejs에서받은 사용자 아이디를 저장하기 위해 Angular로 서비스를 만들고 싶습니다. 각도로 서비스 만들기

그래서 나는 서비스를 만들었습니다

MyApp.service('myservice', function(id) { 
    var userId = id; 
    return userId; 
}); 

을 그리고 내 컨트롤러 : 서비스에 데이터를 저장하는

MyApp.controller("MyCtrl", function($scope, $http, myservice){ 

    $scope.senduser = function(user){ 

     $http.post("/login", user).then(function(response){ 
      if(response.data){ 

      console.log(response.data); 
      myservice(response.data.id); //Store the data received from Node to myservice 

      } else { 
       console.log("No Data"); 
      } 
     }); 
    } 
}); 

임 수 없습니다. 나중에 액세스 할 수 있도록 서비스에 사용자 ID를 저장하려면 어떻게해야합니까?

+1

을 조금도. 이 데이터가 필요한 서비스에 속합니다. – estus

답변

1

서비스 코드는 다음과 같이 할 수 있습니다 당신은 컨트롤러에서 $ HTTP를하지 말았어야

MyApp.controller("MyCtrl", function($scope, $http, myservice){ 

$scope.senduser = function(user){ 

    $http.post("/login", user).then(function(response){ 
     if(response.data){ 

     console.log(response.data); 
     myservice.setUserId(response.data.id); //Store the data received  from Node to myservice 

     } else { 
      console.log("No Data"); 
     } 
    }); 
} 
}); 
+0

먼저 'id is not defined'라고 말합니다. id를 0으로 정의했습니다. myservice.getUserId를 호출하면 아무 것도 호출되지 않으며, function() { return userId; }' – Somename

+1

나는 편집했습니다. 지금 확인하십시오. 또한 getter를 호출 할 때 'myService.getUserId()'와 같은 호출을 할 때 – AshishU

+0

고마워. 지금 일하고있어. – Somename

0

서비스 팩토리 함수는 나머지 응용 프로그램에 대한 서비스를 나타내는 단일 객체 또는 함수를 생성합니다.

서비스 코드를 아래 코드로 변경하십시오.

MyApp.factory('myservice', function() { 
     var userId; 

     setUserId = function(id) { 
      userId = id; 
     } 

     getUserId = function() { 
     return userId; 
     } 

    return { 
    setUserId : setUserId, 
    getUserId : getUserId 
    } 

    }); 

을 그리고 컨트롤러는 설정하고 다음과 같이 값을 얻을 수 있습니다 :

MyApp.service('myservice', function() { 
    // setting some default value 
     this.userId = 0; 
}); 

MyApp.controller("MyCtrl", function($scope, $http, myservice){ 

    $scope.senduser = function(user){ 

    $http.post("/login", user).then(function(response){ 
     if(response.data){ 
     console.log(response.data); 
     myservice(response.data.id); //Store the data received from Node to myservice 
     myservice.userId = response.data.id 

     } else { 
      console.log("No Data"); 
     } 
     }); 
    } 
}); 
+0

Im 'ReferenceError : id is not this.userId = id;'에 대해 – Somename

+0

지금 확인하십시오. –

+0

값이 서비스에 추가되지 않는 것 같습니다. 다른 컨트롤러에서이 코드를 호출 했는데도 여전히 0 – Somename