1

I am getting an error of Cannot read property 'get' of undefined TypeError: Cannot read property 'get'. Which needs to post some data from an endpoint to the table as illustrated on the example from the GitHub.

Here is the api service that I call the get method.

import { Injectable } from '@angular/core';
import { Http, Headers, Request, RequestOptions, RequestMethod, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { AuthService } from './auth.service';
import { environment } from '../../environments/environment';



@Injectable()
export class ApiService {
  private baseUrl = environment.apiUrl;
  constructor(private http:Http, private authService: AuthService) { }

  get(url: string){
    return this.request(url, RequestMethod.Get);
  }

  post(url: string, body: Object){
    return this.request(url, RequestMethod.Post, body);
  }

  put(url: string, body: Object){
    return this.request(url, RequestMethod.Put, body);
  }

  delete(url: string){
    return this.request(url, RequestMethod.Delete);
  }

  request(url: string, method: RequestMethod, body?: Object){
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', `Bearer ${this.authService.getToken()}`);

    const requestOptions = new RequestOptions({
      url: `${this.baseUrl}/${url}`,
      method: method,
      headers: headers
    });

    if(body){
      requestOptions.body = body;
    }

    const request = new Request(requestOptions);

    return this.http.request(request)
     .map((res: Response) => res.json())
  }
}

This is the exact line of code in another service that consume the api GET

  staticQuery(): Observable<IUser[]> {
   return this.api2.get('auth/account/users')
    .map((res: Response) => {
      return res.json();
    });
}

Here is the complete code of the second service

import { Provider, SkipSelf, Optional, InjectionToken } from '@angular/core';
import { Response, Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { HttpInterceptorService, RESTService } from '@covalent/http';
import { ApiService } from '../../../../services/api.service';
import { AuthService } from '../../../../services/auth.service';

export interface IUser {
  _id: string;
  email:string;
  createdAt: Date;
  profile: {
      name: string;
      gender: string;
      location: String;
      picture: {
          // data: Buffer; 
          contentType: string;
      }
    }
}

export class UserService extends RESTService<IUser> {

  constructor(private _http: HttpInterceptorService, api: string,
              private authService: AuthService, 
              private api2: ApiService) {
    super(_http, {
      baseUrl: api,
      path: '/dashboard/users',
    });
  }

  staticQuery(): Observable<IUser[]> {
   return this.api2.get('auth/account/users')
    .map((res: Response) => {
      return res.json();
    });
}
}

export const USERS_API: InjectionToken<string> = new InjectionToken<string>('USERS_API');

export function USER_PROVIDER_FACTORY(
    parent: UserService, interceptorHttp: HttpInterceptorService, api: string,authService: AuthService, 
    api2: ApiService): UserService {
  return parent || new UserService(interceptorHttp, api,authService,api2);
}

export const USER_PROVIDER: Provider = {
  // If there is already a service available, use that. Otherwise, provide a new one.
  provide: UserService,
  deps: [[new Optional(), new SkipSelf(), UserService], HttpInterceptorService, USERS_API],
  useFactory: USER_PROVIDER_FACTORY,
};

You can see all the code here for a previous question I had asked earlier here

My module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { MatSnackBarModule, MatIconModule, MatListModule, MatTooltipModule, MatCardModule, MatButtonModule,
         MatToolbarModule, MatInputModule, MatSlideToggleModule, MatMenuModule,MatSelectModule } from '@angular/material';

import { CovalentLoadingModule, CovalentDialogsModule, CovalentMediaModule, CovalentLayoutModule,
         CovalentSearchModule, CovalentCommonModule } from '@covalent/core';

import { UsersComponent } from './users.component';
import { UsersFormComponent } from './form/form.component';

import { userRoutes } from './users.routes';

import { UserService, IUser, USER_PROVIDER, USERS_API } from './services/user.service';
import { MyaccountComponent } from './myaccount/myaccount.component';
import { AlluserComponent } from './allusers/allusers.component';

export { UsersComponent, UsersFormComponent, UserService, IUser, USER_PROVIDER, USERS_API };
import { ImageUploadModule } from "angular2-image-upload";
import { AuthService } from '../../../services/auth.service';
import { ApiService } from '../../../services/api.service';

@NgModule({
  declarations: [
    UsersComponent,
    UsersFormComponent,
    MyaccountComponent,
    AlluserComponent
  ], // directives, components, and pipes owned by this NgModule
  imports: [
    // angular modules
    CommonModule,
    FormsModule,
    RouterModule,
    // material modules
    MatSnackBarModule,
    MatIconModule,
    MatListModule,
    MatTooltipModule,
    MatCardModule,
    MatButtonModule,
    MatToolbarModule,
    MatInputModule,
    MatSlideToggleModule,
    MatMenuModule,
    MatSelectModule,
    // MdFormFieldModule,
    // covalent modules
    CovalentLoadingModule,
    CovalentDialogsModule,
    CovalentMediaModule,
    CovalentLayoutModule,
    CovalentSearchModule,
    CovalentCommonModule,
    // extra
    userRoutes,
    ImageUploadModule.forRoot(),
  ], // modules needed to run this module
  providers: [
    { provide: USERS_API, useValue: ''},
    USER_PROVIDER,
    AuthService,
    ApiService,
  ],
})
export class UsersModule {}
G B
  • 2,323
  • 3
  • 18
  • 32
  • this.api2 is a service that has all the crud functionality as you can see its the first code on this post(apiService). – G B Oct 16 '17 at 15:59
  • If `this.api2` is `undefined`, please check if it's properly injected. If not, please check your `app.module.ts` or wherever you are configuring dependency injection. – Emin Laletovic Oct 16 '17 at 16:03
  • I can be able to access all the methods I have in apiService like `get`, `post`,`put` and `delete`. I have made all the injection in module. It only don't see the get on `this.api2.get()` – G B Oct 16 '17 at 16:11
  • 1
    Try by renaming the get method to get1 or something. Just in case. I think there is a get method in typescript as well may be its overridden by compoailer when generating javascript. just in case – Aniruddha Das Oct 16 '17 at 16:12
  • @AniruddhaDas Is till get the same error even after making the changes. – G B Oct 16 '17 at 16:19
  • could you please post your `app.module.ts` as well? – Emin Laletovic Oct 16 '17 at 16:22
  • I dont see any major error there. may be a silly mistake killing your time. – Aniruddha Das Oct 16 '17 at 16:23
  • @eminlala updated the `module` , @AniruddhaDas you are right hehe. – G B Oct 16 '17 at 16:27
  • I don't see a subscribe anywhere? – DeborahK Oct 16 '17 at 16:46
  • @DeborahK am using `map` promise for observable to get the data from the api. – G B Oct 16 '17 at 16:49

0 Answers0