Reputation: 123
I'm having some issues with typescript, I have this code:
private loadTeams = function(){
let token = sessionStorage.getItem('token');
if(token !== undefined && token !== null && token !== ''){
this._userService.getUserByToken(token)
.subscribe(user => {
this._teamService.getTeamsByUser(token, user)
.subscribe(data => {
this.teamList = data.data;
}, error => {
});
}, error => {
});
} else {
sessionStorage.removeItem('token');
}
}
And gives me the error:
ERROR TypeError: "_this._teamService.getTeamsByUser is not a function"
In other articles, people tell to use arrow function but I think it is already an arrow function?
I have tried to use let that = this; and then call that instead of this in the second function but it didn't work.
Another thing that I have seen people doing is to use .bind(this) but I don't know where do I do that.
Can someone explain to me why is it happening and how to solve that?
Upvotes: 2
Views: 10110
Reputation: 638
You may have an issue with your _teamService injection or construction. Declaring the loadTeams in different fashions works as long as the service call is not undefined.
So,
loadTeams() { ...
or
loadTeams = function() {...
or
loadTeams = () => { ...
All do work if things are properly initialized.
I did put together a Typescript Scratchpad to play with this, can't get it to fail with either of those, but then again my fake version of the "_teamsService" is initialized.
See typescript example Typescript example. You can replace the function definition any of those three ways and things work just fine.
Upvotes: 1
Reputation: 123
Ok problem fixed. I just used private loadTeams(){...}
like you told me but I don't know why I had to shutdown angular and do ng serve again to work.
Upvotes: 1
Reputation: 56986
When you do this:
private loadTeams = function(){
// this here refers to the function
}
What you should do is this:
private loadTeams() {
// this refers to the instance of the class
}
Alternatively, bind this in the constructor like this:
constructor(/* inject stuff here */) {
this.loadTeams = this.loadTeams.bind(this)
}
private loadTeams = function(){
// this refers to the instance of the class
}
However, I'm not convinced this is your problem.
If this was your problem then this._userService
would be undefined and you would get a null pointer error
when calling undefined.getUserByToken(token)
FYI I've said this 16 times in this post, did you spot this?
Upvotes: -1
Reputation: 1219
Where is this._userService coming from? It probably has not been initialized.
Did you forget to inject it into the constructor?
Upvotes: 0