문제

Angular $ 저장 기능을 사용하려는 Angular Resources로 작업하고 있습니다.

기본적으로 $ save는 모델을 서비스 URL로 다시 보냅니다. 그러나 모델이 서비스로 반환 될 것으로 예상됩니다 (이 작업을 수행하지 않으면 모델이 비어 있음). 메시지와 오류를 컨트롤러에 반환하는 가장 좋은 방법이 궁금했습니다.

내 솔루션은 PHP에 새로운 클래스를 만드는 것이 었습니다. 처리에서 발생하는 오류를 저장하는 오류 배열과 리턴 모델을 저장하는 필드가 있습니다. 그런 다음 콜백 함수로 다시 보내고 처리됩니다.

$scope.ApplyChanges=function(){
   console.log("saving...");
    $scope.user.$save(function(data){
      console.log(data);
      if (data.errors.length>0){
         for (error in data.errors){
            $scope.alerts.push({type:'danger', msg: data.errors[error].msg});
         }
         $scope.user=User.get({id:data.data.UserName});
      } else {
         $scope.user=User.get({id:data.data.UserName});
         $scope.alerts.push({type:'success', msg: "User data saved successfully"});
      }
    }, function(err){
         $scope.alerts.push({type:'danger', msg: "There was a problem saving your data: " + err});
    });

이 라인은 다음과 같습니다. $scope.user=User.get({id:data.data.UserName}); 방금 할당하면 $scope.user 에게 data.data, 사용자는 더 이상 서비스를 사용하지 않았으며 내가 시도했을 때 오류가 발생합니다. ApplyChanges 다시.

그렇다면 이것을 더 겉보기에 할 수있는 방법이 있습니까? 모델을 얻으려면 추가 호출을해야합니다. 오류가있는 경우에만 오류를 보내고 모델을 얻기 위해 추가 콜백이 있어야합니까? 더 좋은 방법이 있습니까?

도움이 되었습니까?

해결책

우선, 서버는 관련성이있는 오류를 반환해야합니다. HTTP 오류 상태 코드 (4xx 및 5xx 코드 참조). 이렇게하면 오류 콜백에서 오류 만 처리합니다.

function onError (response){
    switch (response.status) {
    case 400:
    case 404:
    //etc... 
        response.data.errors.forEach(function(error){
            $scope.alerts.push({type:'danger', msg: error.msg});
        });
        break;
    case 500:
        $scope.alerts.push({type:'danger', msg: "There was a problem saving your data: " + response.data});
        break;
    }
}

즉, $ scope.user는 a $ 리소스 인스턴스, 그러면 서버에서 다시 가져올 필요가 없다면 $ save () 메소드는 객체를 변경하지 않습니다.

서버에서 $ scope.user로 검색된 '사용자'객체에서 값을 복사하려면 Angular.extend ()

angular.extend($scope.user, data) //this updates $scope.user with data attributes.

주목할 가치가 있습니다 angular.extend 필요한 경우 딥 카피를 수행하지 않습니다. jQuery.extend:

jQuery.extend(true, $scope.user, data)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top