【问题标题】:Angular2 - Why does JsonPipe surround model properties with quotes?Angular2 - 为什么 JsonPipe 用引号包围模型属性?
【发布时间】:2016-05-23 20:16:36
【问题描述】:

在 Angular 2 中,我有一个组件订阅返回模型的服务,然后使用 JsonPipe 在

我的代码(假设有正确填充模型的服务):

/* example.ts */
export interface Example {
    id: number;
    description: string;
}

/* example.component.ts */
export class ExampleComponent {
    public example: Object = Object;

    constructor(private _exampleService: ExampleService) {
        this._getExample();
    }

    private _getExample() {
        this._exampleService
            .getExample()
            .subscribe(example => this.example = <Example> example);
    }
}

/* example.template.ts */
<form>
    Description: <textarea>{{example.description | json}}</textarea>
</form>

这将呈现一个如下所示的

              _______________________________
Description: | "this is the description"     |
              ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾

引号没有理由围绕字符串。怎么回事?

【问题讨论】:

  • 尝试asych 管道而不是json 管道。请注意,asych 管道将为您提供 subscribe()

标签: angularjs angular angular2-template


【解决方案1】:

来自 javascript 文档https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

JSON.stringify('foo'); // '"foo"'

现在让我们看看 angular2 源代码:

@Pipe({name: 'json', pure: false})
@Injectable()
export class JsonPipe implements PipeTransform {
  transform(value: any): string { return Json.stringify(value); }
}

https://github.com/angular/angular/blob/master/modules/%40angular/common/src/pipes/json_pipe.ts#L15

https://github.com/angular/angular/blob/master/modules/%40angular/facade/src/lang.ts#L422

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多