【问题标题】:Make your pipe null-safe by returning null when null is passed as value当 null 作为值传递时,通过返回 null 使您的管道为 null 安全
【发布时间】:2016-10-18 00:31:29
【问题描述】:

使用管道时,我得到“NgFor 仅支持绑定到可迭代对象,例如数组”。从 cmets 可以看出,我从 Guenter 获得了帮助,然后我遇到了键管道问题,错误为“TypeError:无法将未定义或 null 转换为对象”。 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 } }

【问题讨论】:

  • 我在你的 Plunker 中没有收到错误。
  • 我已经在我的 Plunker 代码中更新了我的 app.ts,以便现在出现错误。如果您有时间,请看一下。
  • 为什么不使用&lt;template ngFor let-item [ngForOf]="json" let-i="index"&gt; 的密钥管道?这是错误的来源,而不是您使用| keys 管道plnkr.co/edit/bMzfbp4q8ZbzC6LC7brL?p=preview 的管道
  • 谢谢。我已经清理了我的 Plunker 代码plnkr.co/edit/KaXUtFtaR3x3NvYIbh02?p=preview,但我收到了 TypeError: Cannot convert undefined or null to object at the line 6 keys.pipe.ts。我的目标是打印出 {{job.name}}。
  • 谢谢你,Guenter。它现在在 Plunker 上为我工作。我已经更新了我的 Stack Overflow 问题,并在评论部分将您的答案归结为解决方案。

标签: json angular


【解决方案1】:

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

在传递null 时不应抛出管道。检查一下

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

Plunker example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多