What is the advantage of the registration service in app.module.ts versus a separate component in corner4?

For example, if I register a service with app.module.ts, I must do the following to make the service available in the component

app.module.ts

import { AppComponent } from './app.component';
import { MyComponent } from './mycomponent/mycomponent.component';
import { MyService } from './services/myservice.service';


@NgModule({
  declarations: [
    AppComponent,
    MyComponent
  ],
  imports: [
  ],
  providers: [MyService],
  bootstrap: [AppComponent]
})

mycomponent.component.ts

import { Component, OnInit } from '@angular/core';
import { MyService } from '../services/myservice.service';

@Component({
    selector: 'my-selector',
    templateUrl: './mycomponent.component.html',
    styleUrls: ['./my-component.component.scss']
})
export class MyComponent implements OnInit {

    constructor(private _myService: MyService) { }

    ngOnInit() {
        this._myService.test()
    }

}

But I could just register in the component itself to use it without adding anything to app.module.ts

import { Component, OnInit } from '@angular/core';
import { MyService } from '../services/myservice.service';

@Component({
    selector: 'my-selector',
    templateUrl: './mycomponent.component.html',
    styleUrls: ['./my-component.component.scss'],
    providers: [MyService]
})
export class MyComponent implements OnInit {

    constructor(private _myService: MyService) { }

    ngOnInit() {
        this._myService.test()
    }

}

I am curious what is the difference for each path?

+4
source share
1 answer

When you add your service to the root providers of the application, all components will enter the same instance of the service. Thus, only one instance will be created during the application. In this case, you can save statein your service.

Component, , , , instance . state ,

, , .

+5

Source: https://habr.com/ru/post/1685814/


All Articles