Reputation: 1095
This is a case I encounter many times during development.
Suppose I have a component with a service dependency that has some observable properties I need.
I can simply declare and assign them like so:
files$: Observable<...>;
fileTypes$: Observable<...>;
constructor(fileService: FileService) {
this.files$ = fileService.files$;
this.fileTypes$ = fileService.fileTypes$;
}
But in cases of many properties, or where the type of the Observable(the ...
in this case) is long, this can become bloated for no good reason.
I've tried the following solution which would give me automatic type inference:
constructor(fileService: FileService,
public files$ = fileService.files$,
public fileTypes$ = fileService.fileTypes$
) {}
When running, however, I get the following error:
"Can't resolve all parameters for FilemanagerComponent: ([object Object], ?, ?)."
Adding @Optional()
to the parameters hasn't helped.
Another solution would be to simply declare the service as public
, then use its' property in the template, but I don't really like that solution very much as it takes away from the type safety.
Is there some clean way to do this?
Upvotes: 0
Views: 552
Reputation: 691765
You can simply use
files$ = this.fileService.files$;
fileTypes$ = this.fileService.fileTypes$;
constructor(private fileService: FileService) {}
But your first solution is absolutely fine. A good IDE would add the properties declarations for you with a single keyboard shortcut. And having the type declared in the component (rather than only declared in the service) makes the code easier to read and understand, IMHO.
Upvotes: 1