Rxjs 5-简单的Ajax请求 [英] Rxjs 5 - Simple Ajax Request
本文介绍了Rxjs 5-简单的Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从一个简单的ajax请求中获取价值,但我不知道该怎么做。这是代码:
I'm trying to get the value from a simple ajax request, but I don't understand how to do that. Here is the code:
Rx.Observable
.ajax({ url: 'https://jsonplaceholder.typicode.com/posts', method: 'GET', responseType: 'json' })
.subscribe(function(data) { return data.response; });
我到处搜索,没有简单的解释。
I searched everywhere and there is no simple explanation.
谢谢!
推荐答案
可观察到。 ajax
可以通过以下界面接受 string
或 Object
:
Observable.ajax
can accept string
or Object
with the following interface:
interface AjaxRequest {
url?: string; // URL of the request
body?: any; // The body of the request
user?: string;
async?: boolean; // Whether the request is async
method?: string; // Method of the request, such as GET, POST, PUT, PATCH, DELETE
headers?: Object; // Optional headers
timeout?: number;
password?: string;
hasContent?: boolean;
crossDomain?: boolean; //true if a cross domain request, else false
withCredentials?: boolean;
createXHR?: () => XMLHttpRequest; //a function to override if you need to use an alternate XMLHttpRequest implementation
progressSubscriber?: Subscriber<any>;
responseType?: string;
}
下面是示例:
const { Observable, combineLatest } = rxjs; // = require("rxjs")
const { ajax } = rxjs.ajax; // = require("rxjs/ajax")
const { map } = rxjs.operators; // = require("rxjs/operators")
// simple GET request example
const simple$ = ajax('https://httpbin.org/get');
// POST request example
const complex$ = ajax({
url: 'https://httpbin.org/post',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-rxjs-is': 'Awesome!'
},
body: {
hello: 'World!',
}
});
const htmlSubscription = combineLatest(simple$, complex$)
.subscribe(([simple, complex]) => {
const simpleResponse = JSON.stringify(simple.response, null, 2);
const complexResponse = JSON.stringify(complex.response, null, 2);
document.getElementById('root').innerHTML = `
<div>
<span><b>GET</b> https://httpbin.org/get</span>
<pre>${simpleResponse}</pre>
<span><b>POST</b> https://httpbin.org/post</span>
<pre>${complexResponse}</pre>
</div>`;
});
<script src="https://unpkg.com/rxjs@6.2.2/bundles/rxjs.umd.min.js"></script>
<div id="root">loading ...</div>
这篇关于Rxjs 5-简单的Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文