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

时间:2017-06-15 07:57:03

标签: angular typescript nativescript angular2-services

  • 我是nativescript angular2的新手。到目前为止,我遵循了文档和 用listview做静态数据。

  • 我将我的json文件放在app/utils/countries.json

  • 我不知道如何获取解析json的本地文件路径。关于此的建议。

  • 下面我发布了带静态数据的listview代码。

打字稿:

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"}

   ]
}

4 个答案:

答案 0 :(得分:1)

arrList = require("./utils/countries.json")应该做到这一点。 arrList将成为{"countries": [...]}

答案 1 :(得分:1)

下面的代码对我来说是检索本地路径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")

  );      

  }


}         

答案 2 :(得分:0)

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

如果url以〜/

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

使用此功能,您可以根据用户是在线还是离线来替换该网址。

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;
}

答案 3 :(得分:0)

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

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;
}