【问题标题】:convert object to json将对象转换为 json
【发布时间】:2017-08-31 18:52:18
【问题描述】:

如何将对象转换为 JSON 并输出到 html 页面?

public User:UserInfo=
  {
    firstName: "O",
    lastName: "K",
    email: "ol@op.com",
    country: "uk",
    avatarUrl: null,
    receiveNotifications: true
  }

【问题讨论】:

  • 如果您不关心格式 {{User | json}} 应该可以工作,否则请提供更多详细信息
  • @oleg 这是哪个版本的 Angular?
  • @Abdel Angular2/4

标签: html json angular


【解决方案1】:

我希望您在问题中向我们提供了更多细节,但我会在这里尽我所能,请耐心等待!假设您有一个看起来像这样的对象

a.component.ts

public obj = {
     name: "Oleg",
     question: "convert object to json",
     description: "Some cool question about angular and JSON"
}

要呈现这些数据,您的视图应如下所示

a.component.html

<h1> {{ obj.name }} </h1>
<h2> {{ obj.question }} </h2>
<p>  {{ obj.description }} </p>

请注意我的班级成员是如何设置为公开的,这在您要创建应用程序的AoT 构建时很重要。

如果您在理解上有困难,请看我的简化示例。看看这个example

【讨论】:

    【解决方案2】:

    我可以看到你来自 jQuery 世界,但是使用 angular.js 事情变得更加简单,请查看这个 jsFiddle:http://jsfiddle.net/pkozlowski_opensource/ASspB/1/

    使用 angular.js,您可以非常简单地附加事件:

      <input type="button" ng-click="showJson()" value="Object To JSON" />
        and then in your controller:
             $scope.showJson = function() {
            $scope.json = angular.toJson($scope.user);
        }
    

    实际上,使用 angular.js 过滤器可以更轻松地完成此操作,请查看此 jsFiddle:http://jsfiddle.net/pkozlowski_opensource/ASspB/2/,其中包含:

    {{user | json}}
    

    【讨论】:

    • OP 在 Angular 而不是 AngularJS 中
    【解决方案3】:

    您可以尝试以下方法:

    let jsonStr=JSON.stringify(user).
    

    【讨论】:

      猜你喜欢
      • 2017-06-16
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多