Getting an error when adding a value to the rootscope in Typescript.
class TestClass{
this.rootScope: ng.IRootScopeService;
constructor($rootScope){
this.rootScope = $rootScope;
}
addValueToRoot=()=>{
this.rootScope.val1 = "something"; //Error: Property doesn't exist on the IRootScopeService
}
}
That is because (as the compiler says) val1
does not exist on ng.IRootScopeService
. You need to extend it to adapt it to your needs, e.g.
interface MyRootScope extends ng.IRootScopeService {
val1: string
}
Then you can just use this interface in your class:
class TestClass {
this.rootScope: MyRootScope;
...
}
You are probably using TypeScript 1.6 which starts catching this kind of errors.
What I usually do is either:
use $rootScope: any
do ($rootscope as any).val1 = ...
use $rootScope: ng.IRootScopeService & { [name:string]: any };
No.3 adds allowance of additional properties to the type. You can even save it under a type name for reuse:
type IExpandable = { [name:string]:any };
$rootScope: ng.IRootScopeService & IExpandable;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With