为Angular 2实现HTTP服务模拟?

时间:2017-03-10 11:22:16

标签: angular typescript

我试图在Angular中编写一个模型HTTP服务,从JSON文件中获取数据并返回该数据。

import { Request, RequestOptionsArgs, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';    

export const HttpServiceMockup = {

  json = // get data from json file

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    // based on the passed url return some data from the json
    // and wrap that data in a Observable of Response.
    return null;
  }

};

如何进行数据包装以便返回Observable<Response>

3 个答案:

答案 0 :(得分:1)

showActions(){
    return(
        <div className="action -bar">
            <button className="Button-Edit" onClick={()=>{this.setState({clickedCrop : true})}}> Crop </button> 
            <br/> 
            Brightness : <input type="range" min="0" max="1" value={val_brightness} onChange={() => {this.handleChange}}/>  
            <br/> 
            Blur :<input type="range" min="1" max="5" value={val_blur} onChange={() => {this.handleChange}}/>
            <br/>
            <button className="Button-Edit" onClick={()=>{this.setState({flag_grayscale :true})}}> Grayscale</button>
            &nbsp;&nbsp;
            <button className="Button-Edit" onClick={()=>{this.setState({flag_invert :true})}}> Invert </button>
        </div>
    )
}

答案 1 :(得分:1)

更接近您当前的代码

import { Request, RequestOptionsArgs, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';    

export const HttpServiceMockup = {

  let data = [{id:1, name:"John"}];

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    // based on the passed url return some data from the json
    // and wrap that data in a Observable of Response.
    let response = null;
    if (url.indexOf("YOUR_URL_MATCH")>=0) 
      response = new Response({body: JSON.stringify(data)});

    return Observable.of(response);
  }
};

你应该使用什么

import { MockBackend } from '@angular/http/testing';
import { Http, BaseRequestOptions } from '@angular/http';

@NgModule({
  providers: [
     BaseRequestOptions,
     MockBackend,
     {
       provide: Http,
       deps: [MockBackend, BaseRequestOptions],
       useFactory: (backend, options) => { return new Http(backend, options); }
     }
  ],
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App]
})
export class AppModule { }

export class App { 
  constructor(private mockbackend: MockBackend) { 
    let data = [{id:1, name:"John"}];  

    mockbackend.connections.subscribe(connection => {
      if (connection.request.url.indexOf("YOUR_URL_MATCH")>=0) 
        connection.mockRespond(new Response({
          body: JSON.stringify(data)
        }));
    });
  }
}

答案 2 :(得分:0)

一般来说,要将模拟数据包装在Observable中,您只需要执行

const mockData = {
  id: 123
};

return Observable.of(mockData);

在您的服务方法中。

当然,请记得import { Observable } from 'rxjs/Observable';