简体   繁体   中英

Passing value to Injectable extends class in Angular

I have one class like this, the problem i have is that url i should pass from other place

@Injectable()
export class SearchSimpleService extends SearchBaseService {
  protected searchUrl = `${url}/search/single`;
  constructor(http: HttpClient) {
    super(http);
  }
}

And my new class should look like this

@Injectable()
export class SearchSimpleService(url: string) extends SearchBaseService {
  protected searchUrl = `${url}/search/single`;
  constructor(http: HttpClient) {
    super(http);
  }
}

Even here I am doing wrong

export class SearchSimpleService extends SearchBaseService {
  protected searchUrl = `${url}/search/single`;
  constructor(http: HttpClient) {
    super(http);
  }
  searchUrlEnviroment(url: string) {
    return this.searchUrl = `${url}/search/single`;
  }
}

But SearchSimpleService(url: string) I dont think this is proper way and this is not working, can anybody help me about this thanks. I know my syntax is wrong but I dont know where even to start, thanks

It you want pass the url to the service constructor, you can use an InjectionToken , see Dependency Providers and Dependency Injection in Angular for more details. Once you've created the token, you should provide it somewhere, for example:

// search_simple.service.ts

export const SEARCH_SIMPLE_URL = new InjectionToken('SearchSimpleService.url');

@Injectable()
export class SearchSimpleService extends SearchBaseService {
  constructor(
    private readonly http: HttpClient,
    @Inject(SEARCH_SIMPLE_URL) private readonly url: string
  ) {
    super(http);
  }
}
// search_simple.component.ts

@Component({
  providers: [
    SearchSimpleService,
    { provide: SEARCH_SIMPLE_URL, useValue: "my/search/url" }
  ]
  ...
})
export class SearchSimpleComponent {
  constructor(
    private readonly searchService: SearchSimpleService
  ) { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM