我对使用与Angular 2.0相关的JavaScript相当新。我有大约2年的Java经验,所以我熟悉编程(一般)。
在我的应用程序中,我有一个JSON有效负载,我想访问它的数据。通常,在Java中,我可能会创建一个映射来捕获所述数据。
我的问题:如何在Angular(2.0)中捕获数据以在控制器/服务范围内使用?
示例数据:
// Add a new checkout field
function kia_filter_checkout_fields($fields){
$fields['extra_fields'] = array(
'some_field' => array(
'type' => 'text',
'required' => true,
'label' => __( 'Some field' )
),
'another_field' => array(
'type' => 'select',
'options' => array( 'a' => __( 'apple' ), 'b' => __( 'bacon' ), 'c' => __( 'chocolate' ) ),
'required' => true,
'label' => __( 'Another field' )
)
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'kia_filter_checkout_fields' );
// display the extra field on the checkout form
function kia_extra_checkout_fields(){
$checkout = WC()->checkout(); ?>
<div class="extra-fields">
<h3><?php _e( 'Additional Fields' ); ?></h3>
<?php
// because of this foreach, everything added to the array in the previous function will display automagically
foreach ( $checkout->checkout_fields['extra_fields'] as $key => $field ) : ?>
<?php woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); ?>
<?php endforeach; ?>
</div>
我正在尝试将数据用于<strong>“type”
非常感谢!
答案 0 :(得分:1)
首先,您的JSON数据看起来不正确。假设您的应用中的/some/endpoint/here
获取请求返回:
{
"impairments": [
{
"type":"SUCKOUT",
"lowBin":132000000,
"highBin":210000000,
"severity":57
}
]
}
您可以使用简单的控制器,如:
app.controller("yourController", ['$http', '$scope', function($http, $scope) {
$scope.type = null;
$http.get('/some/endpoint/here').then(
function(response) {
//response.data contains all the response data
$scope.type = response.data.impairments[0].type;
},
function() {
//error occured, do something
}
);
}]);
然后在你的控制器中你可以简单地使用:
{{type}}
请注意
出于安全原因,angularJS建议将所有JSON响应作为)]}',\n
加上前缀,并将其剥离。
JSON vulnerability允许第三方网站转换您的JSON 在某些条件下将资源URL转换为JSONP请求。为了对付这个 您的服务器可以使用以下字符串为所有JSON请求加前缀 &#34)]}&#39;,\ n&#34 ;. Angular会在之前自动删除前缀 将其作为JSON处理。
您可以在以下网址了解详情:https://docs.angularjs.org/api/ng/service/$http#security-considerations