2016-12-22 21 views
9

Tôi đang cố gắng lấy giá trị từ một yêu cầu ajax đơn giản, nhưng tôi không hiểu cách thực hiện điều đó. Đây là mã:Rxjs 5 - Yêu cầu Ajax đơn giản

Rx.Observable 
    .ajax({ url: 'https://jsonplaceholder.typicode.com/posts', method: 'GET', responseType: 'json' }) 
    .subscribe(function(data) { return data.response; }); 

Tôi đã tìm kiếm ở khắp mọi nơi và không có giải thích đơn giản.

Cảm ơn!

Trả lời

11

Observable.ajax thể chấp nhận string hoặc Object với giao diện như sau:

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; 
} 

thấy AjaxObservable.ts on GitHub

Và đây là ví dụ:

// simple GET request example 
 
const simple$ = Rx.Observable 
 
    .ajax('https://httpbin.org/get') 
 
    .map(e => e.response); 
 

 
const complex$ = Rx.Observable.ajax({ 
 
    url: 'https://httpbin.org/post', 
 
    method: 'POST', 
 
    headers: { 
 
    'Content-Type': 'application/json', 
 
    'x-rxjs-is': 'Awesome!' 
 
    }, 
 
    body: { 
 
    hello: 'World!', 
 
    } 
 
}).map(e => e.response); 
 

 

 
const htmlSubscription = Rx.Observable.combineLatest(simple$, complex$) 
 
    .subscribe(([simple, complex]) => { 
 
    const simpleResponse = JSON.stringify(simple, null, 2); 
 
    const complexResponse = JSON.stringify(complex, 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/bundles/Rx.min.js"></script> 
 
<div id="root">loading ...</div>

+0

Yup Tôi biết bạn có thể ánh xạ nó hay console.log nó để xem Phản hồi. Xin lỗi tôi đã không giải thích tốt câu hỏi của tôi. Giả sử bạn lưu trữ nó trong một biến. Có cách nào để gọi nó và lấy lại giá trị không? – Mark

+0

Tôi đã sửa câu trả lời của mình, giờ tôi đang sử dụng câu trả lời "dưới dạng biến". Nếu bạn tự hỏi làm thế nào để sử dụng Observables với mã javascript của bạn - hãy xem các ví dụ trong tài liệu https://github.com/Reactive-Extensions/RxJS/tree/master/examples/autocomplete –

+0

Hoặc hãy xem gist này/course - https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 –

1

Bạn muốn sử dụng switchMap ..

const response$ = request$.switchMap((url) => { 
    console.log(url); 
    return fetch(url).then(res => res.json()); 
}); 

switchMap flattens một dòng suối và chuyển đổi nó thành một dòng mà chỉ phát ra các dòng phản ứng bên trong. Nếu một innerStream thứ hai được phát ra, luồng đầu tiên bị giết và luồng thứ hai sẽ tự phát sinh.

Xem bin này mà bản demo trực tiếp yêu cầu qua HTTP .. https://jsbin.com/duvetu/32/edit?html,js,console,output

3

phiên bản nguyên cảo

"dependencies": { 
    "rxjs": "^5.1.0" 
} 

import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/observable/dom/ajax'; 
import 'rxjs/add/observable/combineLatest'; 
import 'rxjs/add/operator/debounceTime'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/startWith'; 
import 'rxjs/add/operator/filter'; 
import 'rxjs/add/operator/switchMap'; 
import 'rxjs/add/operator/catch'; 


const posts$ = Observable 
    .ajax('https://jsonplaceholder.typicode.com/posts') 
    .map(e => e.response); 


    const htmlSubscription = posts$ 
    .subscribe(res => { 
    console.log(JSON.stringify(res, null, 2)); 
    }); 
Các vấn đề liên quan