programing

로컬 json 파일에 데이터를 쓸 수 있는 것은 angular만 있으면 됩니다.

newnotes 2023. 3. 1. 11:30
반응형

로컬 json 파일에 데이터를 쓸 수 있는 것은 angular만 있으면 됩니다.

html 폼에서 각도만 사용하여 "Submit"을 눌러 json 파일에 데이터를 쓰려고 하는데 아무 일도 일어나지 않습니다.각을 사용하여 json 파일을 읽을 수 있지만 파일 작성에 대해서는 잘 모르겠습니다.컨트롤러의 onSubmit():

function onSubmit() {
    $scope.save = function() {
        $http.post('./temp/sample_data.json', JSON.stringify($scope.model)).then(function(data) {
            $scope.msg = 'Data saved';
        });
    };
};

html:

<form name="form" ng-submit="onSubmit()" novalidate>
    <formly-form model="model" fields="fields"></formly-form><br/>
    <button type="submit">Submit</button>
</form>

sample_data.json은 생성되지 않으며 빈 파일을 생성해도 데이터가 채워지지 않습니다.$scope.model에는 데이터가 포함되어 있습니다.도와주시면 감사하겠습니다.고마워, 알론

로컬 json 파일에 데이터를 쓸 수 있는 것은 angular만 있으면 됩니다.

아니요. 로컬 파일 시스템에서 페이지를 실행 중인 경우에도 마찬가지입니다(예:file://myfile.html또는 로컬 웹 서버(예:http://localhost/myfile.html또는http://host-on-my-intranet/myfile.html브라우저 호스팅된 JavaScript 코드에서 파일에 직접 쓸 수 있는 방법은 아직 없습니다.

두 가지 선택지가 있습니다.

  1. 쓸 수 있는 것(서버 등)으로 송신하거나

  2. 로서 제공하다data:URI(가능할 경우)를 우클릭하여 "save as"를 선택할 수 있습니다.."

    이 방법은 다음과 같습니다.data:일부 JSON 텍스트의 URI:

    var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
    

#2의 완전한 예:

var theData = {
  foo: "bar"
};
var theJSON = JSON.stringify(theData);
var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);

var a = document.createElement('a');
a.href = uri;
a.innerHTML = "Right-click and choose 'save as...'";
document.body.appendChild(a);

아니요.

Angular run 클라이언트 측.

서버에 데이터를 쓰는 경우(브라우저와 같은 컴퓨터에 있는 경우에도) 서버 측 코드가 필요합니다.

Javascript에서 로컬 파일 시스템에 직접 액세스할 수 없습니다.이것은 보안상의 이유로 실시되고 있습니다(생각해 보면 일리가 있습니다).

javascript를 통한 로컬 파일 액세스

이것은 불가능하기 때문에 다른 루트를 시도해 볼 수 있습니다.당신의 $스코프.save가 호출되지 않았습니다.연결되었을 뿐입니다.

$scope.save = function() {
  localStorage.model = JSON.stringify($scope.model);
};
function onSubmit() {
  $scope.save();
  $scope.msg = 'saved';
};

초기 설정 시 모델을 되돌리려면 다음 절차를 따릅니다.

if (localStorage.model)
  $scope.model = JSON.parse(localStorage.model);

다음 코드는 JSON 개체의 다운로드 버튼을 추가합니다.

주의: HTML 5에서는 앵커 태그로 버튼을 감싸는 것을 권장하지 않지만, Chrome에서는 동작합니다.YMMV

HTML:

<a download="my-json-object.json" [href]="dataUri">
  <button>Download</button>
</a>

타이프스크립트:

  get dataUri(): SafeUrl {
    const jsonData = JSON.stringify(this.dataSource);
    const uri = 'data:application/json;charset=UTF-8,' + encodeURIComponent(jsonData);
    return this.sanitizer.bypassSecurityTrustUrl(uri);
  }

언급URL : https://stackoverflow.com/questions/30288087/is-it-possible-to-write-data-to-a-locally-json-file-with-nothing-but-angular

반응형