Angular 2 json美化打印过滤器.replace error

时间:2016-10-27 15:02:13

标签: javascript angular

找到这个解决方案,在HTML中做一个漂亮的JSON打印,但是我收到.replace错误。除非我失明,否则我没有看到代码有任何问题。

错误:TypeError: Cannot read property 'replace' of undefined

@Pipe({
  name: 'prettyprint'
})
export class PrettyPrintPipe {
   transform(val) {
    return JSON.stringify(val, null, 2)
      .replace(' ', ' ')
      .replace('\n', '<br/>');
  }
}

嗯,似乎并没有完成它的工作,认为它打印得很漂亮,但却增加了/

enter image description here

2 个答案:

答案 0 :(得分:0)

在应用replace函数之前,您应该检查值的值。

<强>管

@Pipe({
  name: 'prettyprint'
})
export class PrettyPrintPipe {
   transform(val) {
    if(typeof(val) == "undefined") return ''; //check value before process it.
    return JSON.stringify(val, null, 2)
      .replace(' ', '&nbsp;')
      .replace('\n', '<br/>');
  }
}

答案 1 :(得分:0)

检查JSON.stringify()方法是否将JavaScript值转换为JSON字符串..

请注意,您可以改进regular expressions以替换给定JSON中的所有匹配项以获得预期结果:

@Pipe({
    name: 'prettyprint'
})
export class PrettyPrintPipe {
    transform(val) {
        let result = '';
        try { 
            result = JSON.stringify(val, null, 2)
                .replace(/ /g, '&nbsp;')
                .replace(/\\n/g, '&lt;br&gt;');
        } 
        catch (err) {
            console.error(err.message);
        }
        finally { 
            return result; 
        }
    }
}

使用transform()函数的示例:

&#13;
&#13;
var json = {"id":1,"name":"A green door foo \n bar","price":12.50,"tags":["home","green"]},
    transform = function (val) {
      let result = '';
      try { 
        result = JSON.stringify(val, null, 2)
        .replace(/ /g, '&nbsp;')
        .replace(/\\n/g, '&lt;br&gt;');
      } 
      catch (err) {
        console.error(err.message);
      }
      finally { 
        return result; 
      }
    };

// Result empy and logs the error in console
console.log(transform(undefined));

// Transform the provided "val"
console.log(transform('some string with a\nnew line...')); 
console.log(transform(json));
console.log(transform({}));
console.log(transform(true));
console.log(transform(false));
console.log(transform([1, 'false', false]));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;