The inject function in Angular is not just a toy

แชร์
ฝัง
  • เผยแพร่เมื่อ 22 ต.ค. 2024

ความคิดเห็น • 58

  • @JoshuaMorony
    @JoshuaMorony  10 หลายเดือนก่อน

    Join my weekly newsletter here: mobirony.ck.page/4a331b9076

  • @TayambaMwanza
    @TayambaMwanza 10 หลายเดือนก่อน +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.

  • @CubicoOriginal
    @CubicoOriginal 9 หลายเดือนก่อน +7

    Please Joshua, can you make a video about testing componets that are using inject? Ty

  • @LCTesla
    @LCTesla 10 หลายเดือนก่อน +3

    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 9 หลายเดือนก่อน +2

    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 7 หลายเดือนก่อน

      Exactly, I can’t imagine injecting a service everytime a function is called, is a good thing

  • @lakhveerchahal
    @lakhveerchahal 10 หลายเดือนก่อน +1

    I just refactored a guard class to a function and you uploaded a video on the same context! Cool little coincidence 😄

  • @alexandreroy5934
    @alexandreroy5934 8 หลายเดือนก่อน

    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?

  • @kr30000
    @kr30000 8 หลายเดือนก่อน

    This might be pretty handy for the new angular tanstack query

  • @lukaszpiotrluczak
    @lukaszpiotrluczak 10 หลายเดือนก่อน +2

    From when OOP == Class based approach?
    I must have missed something...

  • @pravinmane1
    @pravinmane1 9 หลายเดือนก่อน

    Great and gives new perspective looking at these things ❤

  • @DisturbedNeo
    @DisturbedNeo 9 หลายเดือนก่อน

    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.

  • @ShivamKumar-jj6ln
    @ShivamKumar-jj6ln 4 หลายเดือนก่อน

    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`

  • @karamuto1565
    @karamuto1565 10 หลายเดือนก่อน

    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.

  • @GeoffTripoli
    @GeoffTripoli 9 หลายเดือนก่อน

    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 9 หลายเดือนก่อน

      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

  • @Faheem-Jags
    @Faheem-Jags 5 หลายเดือนก่อน

    I will wait until angular 22 and decide weather to continue with angular or not

  • @yufgyug3735
    @yufgyug3735 10 หลายเดือนก่อน +1

    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  10 หลายเดือนก่อน

      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 10 หลายเดือนก่อน +1

      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)

  • @chaos_monster
    @chaos_monster 10 หลายเดือนก่อน +1

    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.

  • @marcush3997
    @marcush3997 10 หลายเดือนก่อน +4

    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  10 หลายเดือนก่อน +1

      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 10 หลายเดือนก่อน

      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  10 หลายเดือนก่อน +2

      @@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

  • @stephenjames2951
    @stephenjames2951 10 หลายเดือนก่อน +1

    Interesting and useful.

  • @UmamNardi
    @UmamNardi 9 หลายเดือนก่อน

    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  9 หลายเดือนก่อน

      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))

    • @UmamNardi
      @UmamNardi 9 หลายเดือนก่อน

      @@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

  • @ahmedhgazy4773
    @ahmedhgazy4773 9 หลายเดือนก่อน +1

    which editor you use ?

  • @sakubdev52
    @sakubdev52 10 หลายเดือนก่อน

    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

  • @Ba_Dashi
    @Ba_Dashi 10 หลายเดือนก่อน

    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  10 หลายเดือนก่อน

      inject will cause an error if you try to use it outside of an injection context

    • @Ba_Dashi
      @Ba_Dashi 10 หลายเดือนก่อน

      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 7 หลายเดือนก่อน

      It does

  • @gururajmoger8649
    @gururajmoger8649 10 หลายเดือนก่อน

    Please do some courses on angular 17

  • @pqnet84
    @pqnet84 9 หลายเดือนก่อน

    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  9 หลายเดือนก่อน

      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 10 หลายเดือนก่อน +2

    Please zoom a bit your screen. It’s very hard in your videos to see what’s going on. Thanks

  • @napapt
    @napapt 9 หลายเดือนก่อน

    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.

  • @КонстантинХ-у4ф
    @КонстантинХ-у4ф 9 หลายเดือนก่อน

    where is source code ?

  • @rogerwaldron5264
    @rogerwaldron5264 10 หลายเดือนก่อน +10

    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 10 หลายเดือนก่อน +16

      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 10 หลายเดือนก่อน +10

      don't commit unused code...

    • @dany5ful
      @dany5ful 10 หลายเดือนก่อน

      Maybe you don't own the code... Tree shaking libraries is great. Not sure how that apllies to angular tho. ​@@chaos_monster

    • @adambickford8720
      @adambickford8720 10 หลายเดือนก่อน +2

      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 10 หลายเดือนก่อน +1

      That was a dumb comment.

  • @XArthieX
    @XArthieX 10 หลายเดือนก่อน

    Angular using classes is one of the regrets from the angular creator.

  • @antjones2281
    @antjones2281 9 หลายเดือนก่อน +1

    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 9 หลายเดือนก่อน

      "inject" can only be called in an injection context, you can't just call it wherever you like.

    • @antjones2281
      @antjones2281 9 หลายเดือนก่อน

      @@DisturbedNeo I didn't mean that literally. my point still stands.

    • @alekseituichiev9300
      @alekseituichiev9300 หลายเดือนก่อน

      agree all this is going to hell