【问题标题】:How to get the local json file path in angular2 nativescript如何在angular2 nativescript中获取本地json文件路径
【发布时间】:2018-05-26 06:02:09
【问题描述】:
  • 我是 nativescript angular2 的新手。到目前为止,我遵循了文档和 用listview做静态数据。

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

  • 我不知道如何获取本地文件路径来解析 json.Need 建议。

  • 下面我发布了静态数据列表视图的代码。

打字稿:

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

   ]
}

【问题讨论】:

  • 您要导入您在app/utils 文件夹中的 json 文件吗?
  • @mast3rd3mon 是的。我需要解析这个目录 app/utils/countries.json 中的 countries.json 文件。

标签: angular typescript nativescript angular2-services


【解决方案1】:

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

【讨论】:

  • 你可能不需要 ./ 要求字符串
  • 我不知道如何解析数据。我没有找到任何与此相关的示例。我只浏览了与 http 相关的 json 示例。看来这里我不需要那个 http,因为我需要在本地路径中解析它。
  • 什么意思?将arrList分配给countrys.json文件意味着arrList[0].id等于1,arrList[1].id等于2等等
【解决方案2】:

以下代码对我有用,可以检索本地路径 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")

  );      

  }


}         

【讨论】:

    【解决方案3】:

    你也可以使用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;
    }
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 上述“fromPath”调用将在需要时创建文件夹/文件。
      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多