The inject function in Angular is not just a toy

  Рет қаралды 15,790

Joshua Morony

Joshua Morony

Күн бұрын

My Angular course: angularstart.com/
The inject function is a newer way to facilitate dependency injection in Angular, but it provides benefits beyond just being a slightly different syntax for DI. This video discusses one such benefit: being able to use dependency injection within a function.
Get weekly content and tips exclusive to my newsletter: mobirony.ck.page/4a331b9076
Want to build mobile apps with Angular?: ionicstart.com
0:00 Introduction
0:29 Utility function with inject
1:12 Why use a function?
1:49 Class based implementation
2:25 Function vs class based approach
#angular
- More tutorials: modernangular.com
- Follow me on Twitter: / joshuamorony

Пікірлер: 57
@JoshuaMorony
@JoshuaMorony 7 ай бұрын
Join my weekly newsletter here: mobirony.ck.page/4a331b9076
@CubicoOriginal
@CubicoOriginal 7 ай бұрын
Please Joshua, can you make a video about testing componets that are using inject? Ty
@TayambaMwanza
@TayambaMwanza 7 ай бұрын
Thanks for sharing, I've stuck with constructor for now until the angular team settles on something difinitive, but I use inject for functional guards and when I want to provide a configuration service in the root. So my policy right now is constructor by default, inject where classes are deprecated basically.
@lakhveerchahal
@lakhveerchahal 7 ай бұрын
I just refactored a guard class to a function and you uploaded a video on the same context! Cool little coincidence 😄
@pravinmane1
@pravinmane1 6 ай бұрын
Great and gives new perspective looking at these things ❤
@Lamevire
@Lamevire 7 ай бұрын
wouldn't the class approach be more performant because you instantiate and therefore inject services only once instead you would do it for every function call?
@tollington9414
@tollington9414 4 ай бұрын
Exactly, I can’t imagine injecting a service everytime a function is called, is a good thing
@stephenjames2951
@stephenjames2951 7 ай бұрын
Interesting and useful.
@karamuto1565
@karamuto1565 7 ай бұрын
I have some old code with event listeners where I needed to provide services as function parameters. If the inject function would have been a thing at that time I wouldn't have so much boilerplate. Currently I use it for cases with abstract classes so I can get around the overblown super constructor.
@LCTesla
@LCTesla 7 ай бұрын
If a class and its constructor only exists to lend DI context to a function, it's nice to be able to just define it as a function instead. That's what I get from this. It enforces the single responsibility principle by abstracting away from the class construct entirely, capturing an injected service into the closure instead. And it's a hell of a lot less verbose.
@kr30000
@kr30000 5 ай бұрын
This might be pretty handy for the new angular tanstack query
@alexandreroy5934
@alexandreroy5934 5 ай бұрын
Hi Joshua 👋 Is there a performance upgrade if we use the function approach? If I inject only when needed compare to constructor... I know it's not lazy loaded like if(true) import ____ but still?
@lukaszpiotrluczak
@lukaszpiotrluczak 7 ай бұрын
From when OOP == Class based approach? I must have missed something...
@yufgyug3735
@yufgyug3735 7 ай бұрын
if the lesson service used providedIn: 'root', wouldnt that eliminate the need to provide it in the injector of the component? or would it cause some other issues i dont get?
@JoshuaMorony
@JoshuaMorony 7 ай бұрын
You could do this in some cases, but you might not want something provided in root - perhaps just because it is not something you want to be shared, but also specifically for a case like this where you want to utilise info from the ActivatedRoute which should be tied to a specific component
@ChauTran-xc4ld
@ChauTran-xc4ld 7 ай бұрын
provided-in-root-services get their dependencies from the Root Injector and ActivatedRoute does not exist on the Root Injector (it might but it might not be the same instance that the route component has)
@gururajmoger8649
@gururajmoger8649 7 ай бұрын
Please do some courses on angular 17
@ahmedhgazy4773
@ahmedhgazy4773 7 ай бұрын
which editor you use ?
@JoshuaMorony
@JoshuaMorony 7 ай бұрын
neovim
@Faheem-Jags
@Faheem-Jags 2 ай бұрын
I will wait until angular 22 and decide weather to continue with angular or not
@marcush3997
@marcush3997 7 ай бұрын
I might be mistaken but think people (me included) weren’t against functional injection. It’s because the syntax from the last video being too closed to ng1 and it triggered a lot of PTSD 😂
@JoshuaMorony
@JoshuaMorony 7 ай бұрын
Tried not to make this video sound like these two things (this vid/last vid) are equivalent and that the same objections/arguments apply to this one, I just didn't realise the last one would be controversial so wanted to make sure I focused a bit more on the compare/contrast/why in this video
@marcush3997
@marcush3997 7 ай бұрын
You content is awesome :) I bought both angulatstart and ionicstart and they’re amazing especially the reactivity lessons. Would love to see a new course on monorepo + nx in the future if possible ;). Your project structure seems neat and would love to learn about the deets
@JoshuaMorony
@JoshuaMorony 7 ай бұрын
@@marcush3997 thanks! This is definitely something in the works, I plan on covering "extra" things outside of the fundamentals like Nx/monorepos, Analog, Tailwind, Testing, and other advanced stuff - will likely be a while away though
@DisturbedNeo
@DisturbedNeo 6 ай бұрын
The changes the Angular team have been making lately make me think it won't be too long before we see functional components, so it's probably worth getting up to speed with things like signals, inject, and other such functions that are basically just React hooks, so that when that transition inevitably occurs, we won't be completely blindsided.
@Ba_Dashi
@Ba_Dashi 7 ай бұрын
My major question is: what happens if you use a function that calls inject outside of an injection context? Imo anything that needs a specific "context" should be a compilation error, and @injectables definitely provide that.
@JoshuaMorony
@JoshuaMorony 7 ай бұрын
inject will cause an error if you try to use it outside of an injection context
@Ba_Dashi
@Ba_Dashi 7 ай бұрын
Right, and IMO that's a major issue! I wish there was a way to cause a compilation error if you tried to call a function that requires injection outside of an injection context. The way I see it, injection contexts are similar to the colored function problem(async vs non async), but they are hidden behind a runtime error. At least with @Injectable and constructor injection, we're forced to provide the context and so won't be surprised if some deep function calls `inject` unexpectedly. On a large code base with many developers, I can see `inject` causing unexpected breakage because not every case is tested properly.
@paragateoslo
@paragateoslo 4 ай бұрын
It does
@user-os5rj4ks4d
@user-os5rj4ks4d 6 ай бұрын
got error, NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`
@JoshuaMorony
@JoshuaMorony 6 ай бұрын
Yes you can only use the inject() function within an injection context (e.g. most typically inside of the constructor, or in a field initializer above the constructor myThing = inject(Whatever))
@user-os5rj4ks4d
@user-os5rj4ks4d 6 ай бұрын
@@JoshuaMorony i see, so it can't be used and must be initiated first in the component, I think it can be used directly, that makes it more practical
@user-hs9uf8fg5k
@user-hs9uf8fg5k 7 ай бұрын
where is source code ?
@ShivamKumar-jj6ln
@ShivamKumar-jj6ln Ай бұрын
export const JobHandler: Handler = async () => { const module = await import(`@nova/components`); const viewContainer = inject(ViewContainerRef); viewContainer.createComponent(module['LoaderComponent']); console.log('JobHandler is working'); return true; }; Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`
@chaos_monster
@chaos_monster 7 ай бұрын
I personally prefer Mixins over the function based approach, and yes for mixins the inject function is pure gold. One Reason I prefer the mixin approach of the function approach you showed, is IMHO testability. I do agree that a service just for that might be overkill (but was necessary in the past). One last thought, Can someone elaborate what the aversion against `this` is? I hear this way to often as an argument pro FP and con OOP. But Neither is `this` a FP feature I would like to point out nor is `this` the OOP feature one should consider OOP for.
@GeoffTripoli
@GeoffTripoli 7 ай бұрын
One of the reasons I don’t love the function based approach is because the inject function only works in an injection context, (you can only call it while a class is being instantiated), so if you move everything to a function, what’s to prevent another developer from trying to call that function outside of an injection context? Seems, less intuitive to me.
@e-jarod4110
@e-jarod4110 7 ай бұрын
If he calls outside, the app will simply not work and crash But we can say the same for something like hard coded service instancing const datePipe = new DatePipe() This works, but not recommended, so at least there is an error thrown at runtime
@sakubdev52
@sakubdev52 7 ай бұрын
Hmm I mean, the argument of "need to mark this service with decorator and provide it into the providers" is not valid since CLI does that for you already. I'm not hating or stuff like that, I just wonder what is the real benefit of switching to the function base approach except those syntax changes
@rogerwaldron5264
@rogerwaldron5264 7 ай бұрын
Reason for this increasing trend of functions over classes is because it isn't possible for tree shaking to remove unused methods within a class. This isn't just Angular it is all JS frameworks
@chaos_monster
@chaos_monster 7 ай бұрын
I would consider an unused method in a class dead code and would argue always to delete it. That argument sounds like symptome fighting instead of solving the problem or removing dead code
@SeySvK
@SeySvK 7 ай бұрын
don't commit unused code...
@dany5ful
@dany5ful 7 ай бұрын
Maybe you don't own the code... Tree shaking libraries is great. Not sure how that apllies to angular tho. ​@@chaos_monster
@adambickford8720
@adambickford8720 7 ай бұрын
This is more around 3rd party code. If i include a lib that's class based i'm almost certainly using like ~5% of its capability/code.
@LarsRyeJeppesen
@LarsRyeJeppesen 7 ай бұрын
That was a dumb comment.
@pqnet84
@pqnet84 7 ай бұрын
Calling the function directly is not dependency injection, and a code smell. There is no way for example to replace the factory function with a mock for testing
@JoshuaMorony
@JoshuaMorony 7 ай бұрын
Using a helper function that is not provided through DI is not bad design, and the DI that the function does use (ActivatedRoute in this case) can still be swapped out in tests with TestBed
@Developerorium
@Developerorium 7 ай бұрын
Please zoom a bit your screen. It’s very hard in your videos to see what’s going on. Thanks
@napapt
@napapt 6 ай бұрын
Can't understand the angular vs react debate. If there's an upside to the framework fatigue, is that we learn from each other, and listen to the community for a better DX.
@XArthieX
@XArthieX 7 ай бұрын
Angular using classes is one of the regrets from the angular creator.
@antjones2281
@antjones2281 7 ай бұрын
Oh boy... The idea of just "willy-nilly" using inject() all over the place just because its easier , hurts my brain. The concept of inject() is in most DI containers is called "Service Location" and is an anti-pattern. The reason you inject into your constructor is so that at a glance you can easily see the dependencies of your services. Can you imagine a large project looking at one of your services and not being able to see it's dependecies without scanning every line of code for "inject()"? what a nightmare. There are use cases for Service location for sure.. I would use it when implementing the Factory Pattern for example. These abilities to just spawn services out of thin air seems cool at first, but trust me the inject function is like giving you just enough rope to hang yourself with.
@DisturbedNeo
@DisturbedNeo 6 ай бұрын
"inject" can only be called in an injection context, you can't just call it wherever you like.
@antjones2281
@antjones2281 6 ай бұрын
@@DisturbedNeo I didn't mean that literally. my point still stands.
The easier way to code Angular apps
9:54
Joshua Morony
Рет қаралды 65 М.
ngTemplateOutlet is WAY more useful than I realised
16:36
Joshua Morony
Рет қаралды 73 М.
Mom's Unique Approach to Teaching Kids Hygiene #shorts
00:16
Fabiosa Stories
Рет қаралды 37 МЛН
Идеально повторил? Хотите вторую часть?
00:13
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 7 МЛН
How Many Balloons Does It Take To Fly?
00:18
MrBeast
Рет қаралды 205 МЛН
Sigma Kid Hair #funny #sigma #comedy
00:33
CRAZY GREAPA
Рет қаралды 40 МЛН
Angular Inject Function - Better Than Constructor
8:10
Monsterlessons Academy
Рет қаралды 11 М.
WTF is "Zone.js" and is it making your app slow?
13:21
Joshua Morony
Рет қаралды 53 М.
Why I decided to switch to the inject() function in Angular
6:10
Joshua Morony
Рет қаралды 55 М.
3 ways to reduce the size of your docker images
17:20
Raghav Dua
Рет қаралды 8 М.
Why You Shouldn't Nest Your Code
8:30
CodeAesthetic
Рет қаралды 2,6 МЛН
Generics: The most intimidating TypeScript feature
18:19
Matt Pocock
Рет қаралды 169 М.
Why didn't the Angular team just use RxJS instead of Signals?
8:15
Joshua Morony
Рет қаралды 90 М.
Angular 17 is a Completely Different Framework
3:42
Awesome
Рет қаралды 51 М.
Refactoring a React component - Design Patterns
15:19
Cosden Solutions
Рет қаралды 94 М.
The CLEANEST authentication I've ever built with Angular
9:50
Joshua Morony
Рет қаралды 34 М.
Mom's Unique Approach to Teaching Kids Hygiene #shorts
00:16
Fabiosa Stories
Рет қаралды 37 МЛН