how can i use useEffect like hook in angular?
in react we do this:
useEffect(() => {
const fetchUser = async () => {
const res = await axios.get(`/users?id=${post?.userId}`);
setUser(res.data);
};
fetchUser();
}, [post?.userId]);
as we can see this hook will only run when user-id changes, now i want to achieve this same functionality in angular.
in my current code(angular):
ngOnInit(): void {
const res = this.postService.getAllPosts();
this.postService.setPosts(res);
}
i want ngOnInit to run again only when user-id changes.
ngOnInit will run only once in your application, after the ngOnChanges lifecycle hook.
I'm not sure if I understood your question, you want to 'listen' to a class property change and trigger a method?
If you want to accomplish this, you can use a set method to a class property to trigger a method every time it receives a new value. Something like:
export class AppComponent {
set foo(userId: string) {
// Do something here
}
}
You could also use ngDoCheck lifecycle hook, this will be triggered every time a data change in your component happens, although invoking this method multiple times can make your application slower.
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