Giter VIP home page Giter VIP logo

ng2-http's People

Contributors

b264 avatar gitter-badger avatar hboylan avatar iagocanalejas avatar raananw avatar riblee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng2-http's Issues

Dynamic Headers Help

Hi @hboylan ! I really like the app you have done here. I was curious about something. I can't seem to add a Header to a call if I need to include a variable.
Something like :

    @GET('/user')
    @Produces<User>()
    @Headers({
        'Authorization' : 'Bearer ' + this.getToken()
    })
    public getUser(): Observable<User> {
        return
    }

I understand that you can't do it the way I have written above, but I was wondering if you could help me since you have a much better understanding of Typescript than I do.

redundant encodeURIComponent

Hi, I'm playing with your lib (super cool) and I tried to send a Query parameter using

@Query("$size")
It means the page size in APISpark.
It was not working... I checked the network tab in Chrome and the lib was sending "%2524size" which is "$size" URLEncoded twice.

I removed encodeURIComponent from util.js

search.set(encodeURIComponent(key), encodeURIComponent(value));

and it worked.

I put other special characters to test and it encoded them automatically.

Can't get it working

I used example from readme (installed cli and then a generator) and always get asked about the package name to use, even if I pass the parameters to init (ie: generator and mode) swagen init --generator ng1-http --mode typescript

If package is installed question is asked again indefinitely.

Even I tried several different cliente, ng1-http, ng2-http, dotnet-httpclient all same issues.

Finally looking in source code if I pass --defaults I get a mode property not defined error.

C:\Users\nlobo\AppData\Roaming\npm\node_modules\swagen\lib\init\index.js:75
        mode: mode.name,
                  ^

TypeError: Cannot read property 'name' of undefined
    at buildConfig (C:\Users\nlobo\AppData\Roaming\npm\node_modules\swagen\lib\init\index.js:75:19)
    at module.exports (C:\Users\nlobo\AppData\Roaming\npm\node_modules\swagen\lib\init\index.js:109:9)
    at Object.<anonymous> (C:\Users\nlobo\AppData\Roaming\npm\node_modules\swagen\cli.js:32:5)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:420:7)

Any idea of that I would be doing wrong.

No way to inject dependencies

The call to super

  constructor(protected http: Http, private thing: Thing) {
    super(http)
  }

precludes any dependency injection of thing. So while you can certainly consume a REST service, you cannot store anything (such as the logged-in user id) anywhere. So as soon as user navigates to another page, you have no idea who they are any more because you cannot inject a dependency in order to store any data. example: thing.userId = 5;

Headers overriding

Hello!

When implementing service for backend requests I've found out that it'll be great to have feature when you're adding Headers decorator to the method with an opportunity to override headers from DefaultHeaders which are on class. Mostly I'm using application/json as the Content-Type but for several methods I want to use another. Currently ng2-http is appending existing comma-separated list of values in one string.

p.s. it's a suggestion for improvement

Default values don't work

Consider API method defined this way:

@GET('some/resource/{id}')
getSomething(
  @Path('id') id: number = 0,
  @Query('limit') limit: number = 15,
): Observable<Something> {
  return undefined;
}

Default values for id and limit parameters are ignored...

Can't inject dependency - it is undefined

Hi. I'm trying to inject some dependency to the service that extends RESTClient, but seems it doesn't work:

@Injectable()
@BaseUrl('...')
@DefaultHeaders({
    // ...
})
export class JwtService extends RESTClient {

    constructor(
        http: Http,
        @Inject(CONFIG) private config: Config
    ) {
        super(http);

        console.log(this.config); // undefined
    }

    // ...

}

Response Interceptor

How to make a custom interceptor to ng2-http? i need edit the response before you receive a user....

Query params as an object

Consider the following http endpoint:

    @GET('users/{userId}/posts')
    public getPosts(@Path('userId') userId: string,
                             @Query('from') from: string,
                             @Query('to') to: string,
                             @Query('status_id') statusId?: number,
                             @Query('label_id') labelId?: number,
                             @Query('account_id') accountId?: string,
                             @Query('limit') limit: number = 500,
                             @Query('order') order: 'asc' | 'desc' = 'asc',
    ): EndPoint<{posts: Array<Post>}> {
        return undefined;
    }

As you can see, it can contain many query parameters. If I'd like to set just the limit, my code will look this way:

getModulePosts('1', undefined, undefined, undefined, undefined, undefined, 2000);

... what is kind of weird for me. And there is also a second problem here: the default values for limit and order parameters are not set. So here comes my question: can I make it better? Would be great to have something like @Body decorator, but for query params, so I could just pass simple object { limit: 2000 } in this case... Thanks in advance.

@Query for 0

//some my rest service
 @GET(someRoute)
 @Produces<any>()
  getSomething(@Query('pageNumber') pageNumber: number, 
               @Query('pageSize') pageSize: number): Observable<any> {
    return null;
  }

this.someMyRestService.getSomething(0, 0).subscribe(r=>{});

So, as a result my parameters does not sent to server.

Why not return interceptor in @Produces ?

Originally, I thought that we need interceptor in @Produces for creating custom producer. For example:
my server return data like this:

{
  "data": {
    "original": "a",
    "original2": "b"
  }
}

and I have to create interceptor like this :

@GET(route)
@Produces<MockModel>(r => r.json().data as MockModel)

My MockModel

export class MockModel {
  constructor (original:string, original2:string){}
}

But then I looked in rest.service.ts

export function Produces<T>(interceptor?: (res: Response) => void) {
  return function(target: RESTClient, propertyKey: string, descriptor: any) {
    descriptor.producer = (res: Response) => {
      if (interceptor) {
        interceptor(res)
      }
      return <T>res.json()
    }
    return descriptor;
  };
}

Why we need interceptor? Or you missed return ? (return interceptor(res))

How to add more than one @Query

What if instead of

POST http://example.com?a=1
I need
POST http://example.com?a=1&b=2

Is this possible with this library?

Perform async operation within request interceptor

I use the library ng2-http and i'm trying get the CSRF Token from my backend and put him on my request before that is executed.
The code of generic service is like this:

import { Injectable } from '@angular/core';
//import {Http, Headers} from '@angular/http';
import { Http, Response, RequestOptions, Request, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import { RESTClient } from 'ng2-http';


@Injectable()
export class GATRest extends RESTClient {

  token: string;
  csrf: string;

  constructor(protected http: Http) {
    super(http);
  }

  protected requestInterceptor(req: Request): Request {
    console.log("REQUEST GATRest");
    console.log(req);
    // set token if saved in local storage
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.token = currentUser.token;

    req.headers.append('Authorization', 'Bearer ' + this.token);
    req.withCredentials = true;
    if (req.method != 0) {
      this.getCSRFToken(req).subscribe(
        (res) => {
          this.csrf = res;
          console.log("Valor do CSRF retornado " + this.csrf);
          req.headers.append('Set-Cookie', 'XSRF-TOKEN=' + this.csrf);
          req.headers.append('X-XSRF-TOKEN', this.csrf);
          console.log("Valor do Cookie da requisição " + req.headers.get("Set-Cookie"));
          console.log("Valor do Header da requisição " + req.headers.get("X-XSRF-TOKEN"));
          console.log("Vai retornar o Request" + Date.now());
          console.log(req);
          return req;
        });
      console.log("RETORNOU O REQUEST ANTES DO CSRF CHEGAR!!!");
      return req;
    } else {
      return req;
    }
    //console.log("RETORNOU O REQUEST ANTES DO CSRF CHEGAR!!!");
  }

  protected responseInterceptor(res: Observable<Response>): Observable<Response> {
    console.log("RESPONSE GATRest");
    console.log(res);
    return res;
  }

  getCSRFToken(req: Request): Observable<string> {
    console.log("Requisitar CSRF TOKEN");
    return this.http.get("http://localhost:8080/csrf", {
      headers: req.headers
    }).map((res) => res.text());
  }
}

How i return de request for the ng2-http always after get the CSRF token from backend? Thank You

HTTP method is always OPTIONS

I have followed the directions but it always raises EXCEPTION: Response with status: 0 for URL: null maybe because of a CORS problem possibly, but from RESTClient the backend is not sending bad data. I changed the local server's response header to X-Frame-Options: ALLOWALL while troubleshooting and still the same error. It runs a preflight OPTIONS request and stops, no matter what the server returns, it seems. So far not a single GET or POST request has been emitted from ng2-http. Do you have any suggestions?

Double quotes sending data as body in application/x-www-form-urlencoded

Hello.

I'm trying to use this library with a x-www-form-urlencoded form.

[...]
@Injectable()
@BaseUrl([...])
@DefaultHeaders({
  [...]
  'Content-Type': 'application/x-www-form-urlencoded',
})
export class AuthService {
  [...]

  @POST('/login')
  @Produces<LoginPayload>()
  public login( @Body authBody: string) {
    return undefined;
  }
}

And it send in body something like:

"[email protected]&password=password&grant_type=password&client_id=XXX&client_secret=XXX&scope=trust"

Look at the double quotes in the beginning and the end.

I've looked at your code and in utils.ts (l.47) I've found

// Body
var body = null;
if (pBody) {
  body = JSON.stringify(args[pBody[0].parameterIndex]);
}

Maybe check the header and avoid the JSON.stringify if it's x-www-form-urlencoded?

Thanks.

Error Handler

Please guide us how to add handler for Http or self-defined error? Thanks

Provide defaults to params

Such code as following (with default value) is not working:

  @GET('someUrl')
  @Produces<any>()
  public getSomeData(@Query('someParam') someParam: string = 'defaultValue'): Observable<any> {
    return null;
  }

Only tricky implementation will work for now, like:

  public getSomeData(someParam: string = 'defaultValue'): Observable<any> {
    return getSomeDataRemote(status);
  }

  @GET('someUrl')
  @Produces<any>()
  private getSomeDataRemote(@Query('someParam') someParam: string): Observable<any> {
    return null;
  }

Intercept HTTP Response

Need a way to intercept the Response before object mapping occurs.

@Produces<User>((res: Response) => {
  if (res.headers.has('Bearer')) {
    // handle bearer token
  }
})

Empty package on npm?

When I installed ng2-http@latest (v1.0.1) empty package has came:
image
The dist directory is empty, so I get errors like:

TS2307: Cannot find module 'ng2-http'.

Tried it twice, package for v1.0.0 is fine.

Cannot POST multipart/form-data

It is not possible to send multipart/form-data POST requests (using a <input type="file">) because of this code snippet:

if (urlencoded && urlencoded === 'application/x-www-form-urlencoded') {
  body = args[pBody[0].parameterIndex];
} else {
  body = JSON.stringify(args[pBody[0].parameterIndex]);
}

If you want to send multipart requests the browser will handle the headers (set them to multipart/form-data;boundary=...), so the Content-Type header has to be empty.

If you have an <input #file type="file" (change)="upload(file)"> you can create a POST request like this:

upload(input: HTMLInputElement) {
  let file: FileList = input.files[0];
  let formData: FormData = new FormData();
  formData.append('file', file, file.name);
  this.http.post(url, formData, { headers: new Headers() });
}

@Query for object

//some my rest service
 @GET(someRoute)
 @Produces<any>()
  getSomething(@Query('object') queries: SomeObject): Observable<any> {
    return null;
  }

So, when I send to my rest service object and when I added @Query('object') (with object key), I want to see request with all my properties from object that I send to method.

It's really helpful when you have request with many query params and when you want build query in loop (for the example)

In this implementation object transform like this: JSON.stringify(value), but I don't understand why this is necessary? Please describe your position or approve my pull request.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.