6
votes

Parent class

import { BadRequestError } from './../common/bad-request-error';
import { NotFoundError } from './../common/not-found-error';
import { AppError } from './../common/app-error';
import { Http } from '@angular/http';
import { Injectable, OnInit } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { throwError} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private url: string , private http: Http) {
 }

getAll() {
 return this.http.get(this.url).pipe(catchError(this.handleError));
}

delete(id) {
  return this.http.delete(this.url + '/' + id)
   .pipe(
    catchError(this.handleError));
 }

update(resource) {
  return this.http.patch(this.url + '/' + resource.id, 
    JSON.stringify({isRead: true})).pipe(
      catchError(this.handleError));
  }

create(resource) {
 return this.http.post(this.url , JSON.stringify(resource))
   .pipe(
     catchError(this.handleError)
   );

}

 private handleError(err: Response) {
   if (err.status === 404) {
     return throwError(new NotFoundError());
 } if (err.status === 400) {
   return throwError(new BadRequestError(err.json()));
 }
   return throwError(new AppError(err));
 }
}

child Class

 import { DataService } from './data.service';
 import { Http } from '@angular/http';
 import { Injectable } from '@angular/core';

@Injectable({
 providedIn: 'root'
})
export class PostService extends DataService {
  constructor(http: Http) {
    super('https://jsonplaceholder.typicode.com/posts' , http);
 }

}

Getting below error while passing string from child class.

Error: StaticInjectorError(AppModule)[String]:
StaticInjectorError(Platform: core)[String]: NullInjectorError: No provider for String! at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:1062) at resolveToken (core.js:1300) at tryResolveToken (core.js:1244) at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1141) at resolveToken (core.js:1300) at tryResolveToken (core.js:1244) at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1141) at resolveNgModuleDep (core.js:8376) at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:9064) at inject (core.js:1403)

please suggest how to resolve above error.

1
You should declare this string outside of the constructor. Ref below linkNilesh Bandekar

1 Answers

2
votes

Any parameter added to service angular will try to inject this by DI system. DataService considers the base class for api service in this case and we don't need to make it injectable. So just remove the injectable decorator

DataService

export class DataService {

  constructor(private url: string , private http: Http) {
 }
 ...    

}