Тёмный

The inject function in Angular is not just a toy 

Joshua Morony
Подписаться 73 тыс.
Просмотров 15 тыс.
50% 1

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

Опубликовано:

 

31 май 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 56   
@JoshuaMorony
@JoshuaMorony 5 месяцев назад
Join my weekly newsletter here: mobirony.ck.page/4a331b9076
@CubicoOriginal
@CubicoOriginal 5 месяцев назад
Please Joshua, can you make a video about testing componets that are using inject? Ty
@TayambaMwanza
@TayambaMwanza 5 месяцев назад
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 5 месяцев назад
I just refactored a guard class to a function and you uploaded a video on the same context! Cool little coincidence 😄
@LCTesla
@LCTesla 5 месяцев назад
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.
@Lamevire
@Lamevire 4 месяца назад
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 2 месяца назад
Exactly, I can’t imagine injecting a service everytime a function is called, is a good thing
@pravinmane1
@pravinmane1 4 месяца назад
Great and gives new perspective looking at these things ❤
@alexandreroy5934
@alexandreroy5934 3 месяца назад
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?
@stephenjames2951
@stephenjames2951 5 месяцев назад
Interesting and useful.
@kr30000
@kr30000 3 месяца назад
This might be pretty handy for the new angular tanstack query
@karamuto1565
@karamuto1565 5 месяцев назад
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.
@lukaszpiotrluczak
@lukaszpiotrluczak 5 месяцев назад
From when OOP == Class based approach? I must have missed something...
@yufgyug3735
@yufgyug3735 5 месяцев назад
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 5 месяцев назад
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 5 месяцев назад
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)
@Faheem-Jags
@Faheem-Jags 22 дня назад
I will wait until angular 22 and decide weather to continue with angular or not
@gururajmoger8649
@gururajmoger8649 5 месяцев назад
Please do some courses on angular 17
@DisturbedNeo
@DisturbedNeo 4 месяца назад
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.
@marcush3997
@marcush3997 5 месяцев назад
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 5 месяцев назад
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 5 месяцев назад
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 5 месяцев назад
@@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
@user-os5rj4ks4d
@user-os5rj4ks4d 4 месяца назад
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 4 месяца назад
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 4 месяца назад
@@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
@Ba_Dashi
@Ba_Dashi 5 месяцев назад
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 5 месяцев назад
inject will cause an error if you try to use it outside of an injection context
@Ba_Dashi
@Ba_Dashi 5 месяцев назад
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 2 месяца назад
It does
@GeoffTripoli
@GeoffTripoli 5 месяцев назад
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 4 месяца назад
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
@ahmedhgazy4773
@ahmedhgazy4773 5 месяцев назад
which editor you use ?
@JoshuaMorony
@JoshuaMorony 5 месяцев назад
neovim
@user-hs9uf8fg5k
@user-hs9uf8fg5k 5 месяцев назад
where is source code ?
@chaos_monster
@chaos_monster 5 месяцев назад
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.
@rogerwaldron5264
@rogerwaldron5264 5 месяцев назад
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 5 месяцев назад
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 5 месяцев назад
don't commit unused code...
@dany5ful
@dany5ful 5 месяцев назад
Maybe you don't own the code... Tree shaking libraries is great. Not sure how that apllies to angular tho. ​@@chaos_monster
@adambickford8720
@adambickford8720 5 месяцев назад
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 5 месяцев назад
That was a dumb comment.
@sakubdev52
@sakubdev52 5 месяцев назад
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
@pqnet84
@pqnet84 5 месяцев назад
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 5 месяцев назад
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 5 месяцев назад
Please zoom a bit your screen. It’s very hard in your videos to see what’s going on. Thanks
@napapt
@napapt 4 месяца назад
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 5 месяцев назад
Angular using classes is one of the regrets from the angular creator.
@antjones2281
@antjones2281 4 месяца назад
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 4 месяца назад
"inject" can only be called in an injection context, you can't just call it wherever you like.
@antjones2281
@antjones2281 4 месяца назад
@@DisturbedNeo I didn't mean that literally. my point still stands.
Далее
Angular in 100 Seconds
2:00
Просмотров 714 тыс.
BRAWL STARS x DRAGONFORCE: A Draco Tale
03:46
Просмотров 9 млн
КОРОЧЕ ГОВОРЯ, 100 ДНЕЙ В СССР 2
08:37
Deferrable Views - New Feature in Angular 17
15:31
Просмотров 16 тыс.
The mindset you need for a DECLARATIVE code refactor
7:56
Understand Angular Signals in 20 Minutes
20:17
Просмотров 6 тыс.
Why You Shouldn't Nest Your Code
8:30
Просмотров 2,5 млн
Looking Into a REAL Codebase - Beyond the Basics
10:12