如何在angular2 nativescript中获取本地json文件路径

How to get the local json file path in angular2 nativescript

打字稿:

import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";

@Component({
    selector: "ns-app",
    templateUrl: "app.component.html",
})
export class AppComponent implements OnInit {

 arrList: Array<Object> = [];

  ngOnInit() {
    this.arrList.push({ name: "India" });
    this.arrList.push({ name: "Sri Lanka" });
  }

 }

HTML:

<page-router-outlet></page-router-outlet>

<GridLayout>
  <ListView [items]="arrList" class="small-spacing">
    <ng-template let-item="item">
      <Label [text]="item.name" class="medium-spacing"></Label>
    </ng-template>
  </ListView>
</GridLayout>

countries.json: (app/utils/countries.json):

{
  "countries": [
              {"id":1,"name":"india"},
              {"id":2,"name":"Sri Lanka"}

   ]
}

arrList = require("./utils/countries.json") 应该可以解决问题。 arrList 将变为 {"countries": [...]}

您也可以使用import { Http } from "@angular/http";

如果 url 以 ~/

开头,NativeScript 的 NSHttp 对象将在本地文件系统中查找

有了这个,您可以根据用户是在线还是离线来替换 url。

getCountries(): Promise<any>  {
        return this.http.get("~/utils/countries.json", this.createRequestOptions())
            .toPromise()
            .then(resp => 
                resp.json()
            )
            .catch((error) => { 
                console.log(error);
            });
}

private createRequestOptions() {
    let headers = new Headers();
    // set headers here e.g.
    //headers.append("AuthKey", "my-key");
    //headers.append("AuthToken", "my-token");
    headers.append("Content-Type", "application/json");

    let options = new RequestOptions({ headers: headers });
    return options;
}

下面的代码让我检索本地路径 json 对象并将其显示在命令提示符下。

getdata.component.ts

   import {Injectable} from "@angular/core";
import {Http,Response} from '@angular/http';
import { HttpModule }      from '@angular/http';

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/startWith';
import 'rxjs/Rx';

@Injectable()
   export class GetData {


constructor(private _http:Http) {

}


 getObjectData() {

 return this._http.get('/utils/countries.json')
   .map(data => console.log("Test", JSON.stringify(data.json())));

} 

}                           

app.component.ts:

import { Component, OnInit, ViewChild } from "@angular/core";

 import { GetData } from './pages/getData.component';
 import { Observable } from 'rxjs/Observable';
 import {Http,Response, RequestOptions} from '@angular/http';

 @Component({
    selector: "ns-app",
    templateUrl: "app.component.html",
    styleUrls: ["./app.css"],
    providers: [GetData]
 })

  export class AppComponent implements OnInit {

     setData : string;
     objectData : any;

     constructor(public getData: GetData, private http: Http) {
   
  }

  ngOnInit() {

   console.log("first", "Test");

   this.getData.getJsonObject()
  .subscribe(data => this.getData = JSON.stringify(data),
   error => alert(error),
   () => console.log("finished")

  );      

  }


}         

实际上你可以从文件中同步读取,例如:

import * as fs from 'tns-core-modules/file-system';

const countries = this.getJSONdata("countries.json");

getJSONdata(fileName: string) {
   const folder = this.getFolder("utils");
   const jsonFileName = fs.path.join(folder.path, fileName);
   const jsonFile = fs.File.fromPath(jsonFileName);
   const data = jsonFile.readTextSync().trim();
   if (data.length === 0) { data = "[]"; }

   return JSON.parse(data);
}

getFolder(folderName: string) {
   const path = fs.path.join(fs.knownFolders.currentApp().path, folderName);
   const folder = fs.Folder.fromPath(path);

   return folder;
}