2016-05-23 46 views
0

在Angular 2中,我有一个组件订阅返回模型的服务,然后使用JsonPipe在<textarea>中显示模型属性。出于某种原因,显示的属性被引号包围。这是为什么发生?Angular2 - 为什么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> 

这将呈现一个< textarea的>,看起来像这样:

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

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

+1

尝试'asych'管,而不是'json'管。请注意,'asych'管道将为你订阅()。 –

回答

2

从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

相关问题