akveo / ng2-smart-table

Angular Smart Data Table component
https://akveo.github.io/ng2-smart-table/
MIT License
1.63k stars 876 forks source link

How to pass headers in Server Data Source API call? #902

Open malik-umair opened 5 years ago

malik-umair commented 5 years ago

I need to send User Auth token to server to fetch user related data and set permissions. I tried to follow this discussion https://github.com/akveo/ng2-smart-table/issues/614 but it's giving error that:

Type 'Headers' is not assignable to type 'import("c:/xampp/htdocs/utahrunning/utahclient/node_modules/@angular/http/src/headers").Headers'. Property 'keys' is missing in type 'Headers'.

I cannot understand what this error really mean. I also posted this question on StackOverFlow but they all are referring to follow above mentioned ticket. Please help and guide what I'm missing. Thanks!

salehasadi commented 5 years ago

@malik-umair Hi, did you find any solution!?

malik-umair commented 5 years ago

@salehasadi No, I'm handling it by passing user id in end URL and at server side I check user role by it's ID. Bad approach but had no other choice.

salehasadi commented 5 years ago

@malik-umair that's weried cause it's using httpClient from angular/common but interceptor does not affect it!

eboakyegyau commented 5 years ago

@malik-umair @salehasadi did you find any solution, the interceptor i use does not affect it either

salehasadi commented 5 years ago

@malik-umair no I found nothing. even if I find a way that's not efficient for me cause I have to process media urls in purpose of dlisplay them so I just get 50000 data per request. It's not so good but works |-O

malik-umair commented 5 years ago

@gyab12 No I didn't found any yet. still looking for a solution. Yeah I tried the interceptor too, that didn't worked for me either.

osmelnp87 commented 5 years ago

here are a solution: https://github.com/akveo/ng2-smart-table/issues/614#issuecomment-372801099

afgoulart commented 5 years ago

Problem:

protected requestElements(): Observable<any> {
    let httpParams = this.createRequesParams();
    return this.http.get(this.conf.endPoint, { params: httpParams, observe: 'response' });
}

Resolve:

protected requestElements(): Observable<any> {
    let httpParams = this.createRequesParams();
    return this.http.get(this.conf.endPoint, { 
        params: httpParams, 
        observe: 'response', 
        ...(this.config.httpOptions || {})
    });
}

https://github.com/akveo/ng2-smart-table/blob/53ea3a9c3229400a9bfcc64665298d543e0c27d2/src/ng2-smart-table/lib/data-source/server/server.data-source.ts#L74

malik-umair commented 5 years ago

@osmelnp87 solution worked for me. Thanks!

eboakyegyau commented 5 years ago

@malik-umair please can you share a snippet? will really appreciate now i still have to attach API key at the end of url which is really bad

malik-umair commented 5 years ago

@gyab12

I've added following code in my component.ts file to send token in header:

Import following packages:

import { ServerDataSource } from 'ng2-smart-table';
import { ServerSourceConf } from 'ng2-smart-table/lib/data-source/server/server-source.conf';
import { Http, Headers, RequestOptions, XHRBackend, BrowserXhr, ResponseOptions, CookieXSRFStrategy } from '@angular/http';

Set following variables:

source: ServerDataSource;
sourceConf: ServerSourceConf;

The following is the code:

fetchRequests() {
    const headerss = new Headers();
    headerss.append('Authorization', `Bearer ${localStorage.getItem('auth_app_token')}`);
    const options = new RequestOptions({
       headers: headerss
    });
    const connection = new XHRBackend(new BrowserXhr(), new ResponseOptions(), new CookieXSRFStrategy());
    this.http = new Http(connection, options);

    this.sourceConf = new ServerSourceConf({
        endPoint: environment.ApiBaseUrl + 'fetchapplications',
        totalKey: 'total',
        dataKey: 'data'
   });
   this.source = new ServerDataSource(this.http, this.sourceConf);
  }
eboakyegyau commented 5 years ago

@malik-umair thanks man

manishlogan commented 5 years ago

@malik-umair I have tried the solution that you have provided, but then am getting the following error: Type 'Http' is missing the following properties from type 'HttpClient': handler, jsonp

@gyab12 Did the code changes work fine for you?

malik-umair commented 5 years ago

@manishlogan have you also added first three import lines of code too which I mentioned?

manishlogan commented 5 years ago

@malik-umair Yes, I did. I am on the latest version of ng2-smart-table, and when I debug the code, I can see that the constructor is expecting HttpClient and not Http, which is the reason I see that error.

To fix I have added a custom Server Data source, and have overriden the two methods.

eboakyegyau commented 5 years ago

@manishlogan maybe this can help,

import { Injectable, Injector } from "@angular/core"; import {HttpRequest, HttpHandler, HttpEvent,HttpInterceptor,} from "@angular/common/http"; import { Observable } from "rxjs/Observable"; import { X_DREAMFACTORY_API_KEY } from "./config/constants";

@Injectable({providedIn: 'root'}) export class TokenInterceptor implements HttpInterceptor { constructor(private injector: Injector) {}

intercept( request: HttpRequest, next: HttpHandler ): Observable<HttpEvent> {

const headers = request.headers
.set('Content-Type', 'application/json' )
.set('X-DreamFactory-API-Key', X_DREAMFACTORY_API_KEY);

const authReq = request.clone({ headers }); // console.log(request); // console.log(headers); // console.log(authReq); return next.handle(authReq);

} }

mot-art commented 5 years ago

@manishlogan the solution with Http instead of HttpClient works for the smart-table version <= 1.2.1 but it's not a good idea, there are deprecation warnings from Angular

could you contribute your solution with pull request?

naseriatalebi commented 5 years ago

best way is to customize server.data-source.ts (create it in your module and import in example-list.coponent.ts and ....) this one: https://github.com/akveo/ng2-smart-table/blob/53ea3a9c3229400a9bfcc64665298d543e0c27d2/src/ng2-smart-table/lib/data-source/server/server.data-source.ts#L74 just set token app-wide(httpInterceptor) change get to post if you need change parameters of body of post/get base your server for paginate change addPagerRequestParams() for sort change addSortRequestParams() for filter change addFilterRequestParams() too I change htttpParams to an object and pass to post/get for body

salehasadi commented 4 years ago

this worked finally to me: https://github.com/akveo/ngx-admin/issues/1959#issuecomment-451174660

theromis commented 4 years ago

My solution is :

export class HeadersServerDataSource extends ServerDataSource {
  httpHeaders: HttpHeaders
  constructor(protected http: HttpClient, headers: HttpHeaders, conf: ServerSourceConf | {} = {}) {
    super(http, conf);
    this.httpHeaders = headers
  }

  protected requestElements(): Observable<any> {
    let httpParams = this.createRequesParams();
    return this.http.get(this.conf.endPoint, { params: httpParams, headers: this.httpHeaders, observe: 'response' });
  }
}
theromis commented 4 years ago

PR created https://github.com/akveo/ng2-smart-table/pull/1188/files