Typescript Angular 2中组件和可注射体之间的通信
在ng2中处理组件和服务通信时,我正在寻找“最佳实践”类型的建议 比如说,我有以下几点:Typescript Angular 2中组件和可注射体之间的通信,typescript,angular,Typescript,Angular,在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
//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
) {}
}
我考虑的是后者,因为它感觉视图与服务完全分离,然而,我看到一些评论,人们更喜欢最初的方法。此外,在某些情况下,\u authService
也可能有一些数据需要绑定到视图,在这种情况下,视图可以检测到对该数据的更改的唯一方法是直接绑定到\u authService
在这两者之间创建通信时,哪种方法被认为是最佳做法?最佳做法是让服务私有化,并使用组件中的方法调用服务。通常,变量名中的下划线表示它是私有的
constructor (
private _authService: AuthService
) {}
这使您的代码更加模块化。如果您决定使用差异服务或编写自己的逻辑来做同样的事情,则不必更新模板中的HTML。您只需更新您的方法
<button (click)="login()">Login</button>
export class LoginComponent {
constructor (
public _authService: AuthService
) {}
login() {
this._authService.login();
}
}
constructor (
private _authService: AuthService
) {}