当null作为值

时间:2016-10-18 00:31:30

标签: json angular

在使用管道时,我得到“NgFor仅支持绑定到诸如阵列之类的Iterables”。从评论中我可以看到Guenter的帮助,然后我遇到了错误“TypeError:无法将undefined或null转换为object”的密钥管道问题。然后,Guenter建议通过在将null作为值传递时返回null来使管道为null安全。

Here is my code on Plunker.

我正在尝试打印批处理作业的名称in JSON format located here.

以下是Plunker上的app.ts:

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule }    from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';

import { JobListComponent }      from './job-list.component';
import { KeysPipe }          from './keys.pipe';
import { JobService }          from './job.service';
import { Job }          from './job';
import { routing } from './app.routes';

@Component({
  selector: 'my-app',
    template: `
    <div>
      <header>
        <div>
          <!-- Title -->
          <span>Jobs::</span>        
                <div>
                  {{jobs | json}}
                  <ul>
                    <li *ngFor="let job of jobs | keys">
                      <a>{{job.name}}</a>
                   </li>
                 </ul> 
              </div>
        </div>
      </header>
  </div>
  `,
})
export class App {
  private json;

  jobs: Observable<Job[]>;

  constructor(private jobService: JobService) {}


    ngOnInit() {

        this.jobService.listJobs()
            .subscribe(
                jobs => {
                    this.jobs = jobs,
                        console.log(this.jobs)
                    console.log("AFTER")
                });

    }


}

@NgModule({
    imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  declarations: [ App,KeysPipe ],
  providers: [JobService],
  bootstrap: [ App ]
})
export class AppModule {}

我正在使用管道,我正在尝试打印作业名称。根据Guenter的建议进行修改:

import {Component, Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
    transform(value: any, args?: any[]): any[] {
      if(value == null) {
        return;
      }
        let keys = Object.keys(value),
            data = [];

        keys.forEach(key => {
            data.push(value[key]);
        });

        return data;
    }
}

这是服务:

import { Injectable }    from '@angular/core';
//import { Jsonp, URLSearchParams } from '@angular/http';
import {Http, Response} from '@angular/http';
import { Job } from './job'
import 'rxjs/add/operator/map';
import {Observable} from "rxjs";


// Decorator to tell Angular that this class can be injected as a service to   another class
@Injectable()
export class JobService {

  // Class constructor with Jsonp injected
  constructor(private http:Http) { }

  // Base URI for Spring Batch Admin
  private jobsUrl = 'https://api.myjson.com/bins/1n6lw';

  // Get the list of jobs
  listJobs() {
        // RESTful service, list of jobs:
        // http://localhost:8080/batch/jobs.json
        const endPoint = 'jobs.json'

       // Return response
      return this.http.get(this.jobsUrl)
          .map(res => <Job[]> res.json().jobs.registrations);

    }

  }

这是我试图解析的JSON。我正在尝试打印{{job.name}}:

{ "mecConsolidatorKickoutJob": { "name": "mecConsolidatorKickoutJob", "resource": "http://localhost:8080/batch/jobs/mecConsolidatorKickoutJob.json", "description": "No description", "executionCount": 460, "launchable": false, "incrementable": false }, 
  "meceinJob": { "name": "meceinJob", "resource": "http://localhost:8080/batch/jobs/meceinJob.json", "description": "No description", "executionCount": 125, "launchable": false, "incrementable": false }, 
  "mecmdwJob": { "name": "mecmdwJob", "resource": "http://localhost:8080/batch/jobs/mecmdwJob.json", "description": "No description", "executionCount": 701, "launchable": false, "incrementable": false }, 
  "mecmdwvalidatingJob": { "name": "mecmdwvalidatingJob", "resource": "http://localhost:8080/batch/jobs/mecmdwvalidatingJob.json", "description": "No description", "executionCount": 1998, "launchable": false, "incrementable": false }, 
  "mecssnJob": { "name": "mecssnJob", "resource": "http://localhost:8080/batch/jobs/mecssnJob.json", "description": "No description", "executionCount": 217, "launchable": false, "incrementable": false } }

1 个答案:

答案 0 :(得分:0)

在解析所有绑定或使用从异步调用接收的输入之前,或者因为从未将值分配给属性之前,传递给管道的参数可以是null

传递null时不应抛出管道。请检查

transform(value) {
  if(!value) {
    return;
  }
  // process values that are != null here
  return result;
}

Plunker example