首页 文章

使用* ngFor检索和显示json对象

提问于
浏览
0

我想从angular2中的json文件中检索信息 . 为此,我创建了这个自定义管道,按照示例How to display json object using *ngFor

import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({name: 'parseData'})


export class ParseDataPipe implements PipeTransform{
    constructor(){}

    transform(value, args:string[]) : any {

       let keys = [];

         for (let key in value) {
            keys.push({
                 key: key,
                 value: value[key]
            });
         }
         return keys;

    }

}

这是我在组件中使用的模板:

<button (click)="onTestGet()">GET REQUEST</button><br>
            <p>{{getData}}</p>

        <button (click)="onTestPost()">POST REQUEST</button><br>
            <p>{{postData}}</p>

        <span *ngFor="#entry of postData | parseData">
            <ul>
                    <!--<li>Key: {{entry.key}}, value: {{entry.value.status}}</li>;-->
                    <li>Value: {{entry.value}}</li>
            </ul>
        </span>
    </div>

这是我的json文件:

{"status":"success","type":"cellSetData","data":    {"epoch":6874,"cube":"EquityDer","axes":[{"id":-1,"hierarchies":  [{"dimension":"Measures","hierarchy":"Measures"}],"positions":  [[{"namePath":["pnl.SUM"],"captionPath":["pnl.SUM"],"properties":   {"DISPLAY_INFO":0}}]]}],"cells":[{"ordinal":0,"value":-42973.21272120108,"formattedValue":"-42,973.21","properties":{}}],"defaultMembers":[{"dimension":"Measures","hierarchy":"Measures","path":["contributors.COUNT"],"captionPath":["Count"]},{"dimension":"Time","hierarchy":"HistoricalDates","path":["Mon Apr 11 02:00:00 CEST 2016"],"captionPath":["2016-04-11"]},{"dimension":"Epoch","hierarchy":"Epoch","path":["master"],"captionPath":["master"]}]}}

我想检索例如“status”和“type”,但我检索一个像这样的字符数组:

值:{值:“值:s值:t值:a值:t值:u值:s值:”值::值:“值:s值:u值:c值:c值:e值: s Value :s Value :“ Value :, Value :”......

我解析像我检索的对象:

postJSON(){
          var param=JSON.stringify(
            {"mdx":"SELECT FROM [EquityDerivativesCube] WHERE ([Measures].[pnl.SUM])"}
          );

          var firstheaders = new  Headers();

          firstheaders.append('Content-Type', 'application/json');
          firstheaders.append('Authorization', 'Basic YWRtaW46YWRtaW4=');

        return this._http
            .post('http://localhost:9090/webservices/pivot/rest/v1/cube/query/mdx', param,{headers: firstheaders})
            .map(res => res.json());

    }

有谁知道为什么我检索一个字符数组而不是像我想要的字符串数组?我想指定我遵循以下示例:access key and value of object using *ngFor Deep nested json to array in array / json rendering of Angular 2 *ngFor

我认为这不是解析json的问题,而是检索它以显示...

谢谢你的帮助

1 回答

  • 2

    我不知道如何获取数据,但似乎你忘记解析它们(即将它转换为JSON对象),因为你遍历字符串而不是对象 .

    在你的循环中,第一个元素是 { 内容的第一个字符,第二个是 " ,依此类推......

    要加载您的JSON文件,您应该使用类似的东西:

    this.http.get('/myfile.json').map(res => res.json());
    

相关问题