Here's where i use my service to get api data to child. Initially it gets the Id and other user data in console.
ngOnInit(): void {
this.commonService.userSetChange.subscribe(
apiData => {
this.getUserSeminar(apiData);
this.user = apiData;
console.log(this.user)
});
}
Then i store it with this variable.
user: any;
Add method to pass the user
variable
addSeminar(): void {
console.log(this.user.id)
event.preventDefault();
const seminar = {
id: null,
user_id: this.user.id,
dates: null,
name: null,
certificate_number: null,
edit: true,
};
this.userSeminars.push(seminar);
const a = this.userSeminars.length - 1;
}
But when i press the addSeminar button
<button (click)="addSeminar()">Add Seminar <i ></i></button>
This gives me api/users/seminar/null 500
CodePudding user response:
The way you strcuture your code led to the status you are in. The sreenshot is explanatory. The undefined
log belongs to the console.log(this.user.id)
in the method named addSeminar(){}
. The null is a value set from your server because you sent nothing to it. However, the first part of the screenshot includes the id:1
which is what you want to pass to the addSeminar(){}
I guess.
You have to move the addSeminar(){}
inside the subscription
inside the ngOnInit(){}
and under the this.user = apiData;
line you pass your parameter to the addSeminar(){}
. If you do not like to have a fat function there, you can just add an argument to the addSeminar(userId: string|number){}
keep it where it is and just call it in the place I pointed to above.
So your logic will be
ngOnInit(): void {
this.commonService.userSetChange.subscribe(
apiData => {
this.getUserSeminar(apiData);
this.user = apiData;
console.log(this.user)
this.addSeminar(this.user?.id) // see this line
});
}
PS: avoid type any
as much as possible. You can set unknown
it is better than any