【问题标题】:Communication Between Components and Injectables in Angular 2Angular 2 中组件和可注射物之间的通信
【发布时间】:2023-03-10 01:45:01
【问题描述】:

在处理 ng2 中的组件和服务通信时,我正在寻找“最佳实践”类型的建议。

假设,例如,我有以下内容:

//auth.service.ts
import {Injectable} from 'angular2/core';

@Injectable()
export class AuthService {

    login() {
       //do some login stuff here
    }

}

//login.component.ts
import {Component} from 'angular2/core';
import {AuthService} from './path/to/auth.service';

@Component({

    selector: 'app-login',
    template: '<button (click)="">Login</button>',
    providers: [AuthService]

})

export class LoginComponent {

    constructor (
    public _authService: AuthService
    ) {}

}

我的问题主要围绕这个:

<button (click)="">Login</button>

我应该只做(click)="_authService.login()" 之类的事情,还是应该在 LoginComponent 内部创建一个登录方法并在视图中引用它?

<button (click)="login()">Login</button>

export class LoginComponent {

    constructor (
    public _authService: AuthService
    ) {}

    login() {
    this._authService.login();
    }

}

我认为是后者,因为感觉视图与服务完全分离,但是,我看到人们更喜欢初始方法的 cmets。此外,在某些情况下,_authService 可能还有一些数据需要绑定到视图,在这种情况下,视图可以检测到数据更改的唯一方法是直接绑定到 _authService

在这两者之间建立通信时,哪种方法被认为是最佳实践?

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    最佳做法是将服务设为私有并使用组件中的方法来调用服务。通常变量名中的下划线表示它是私有的。

    constructor (
        private _authService: AuthService
        ) {}
    

    这使您的代码更加模块化。如果您决定使用不同的服务或编写自己的逻辑来做同样的事情,您将不必去更新模板中的 HTML。您只需更新您的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2021-03-02
      • 2018-02-08
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 2018-10-13
      相关资源
      最近更新 更多