问题描述
因此,我正在查看一个使用Angular 2和Typescript的ionic 2项目,并且对如何设置成员属性有些困惑.看下面的示例,Angular会自动将依赖项注入到构造函数参数中.对于nav,我们将实例成员nav显式设置为构造函数传递的内容.在使用Firebase身份验证的情况下,我们没有将其显式设置为成员变量,但是我们仍然可以通过登录方法中的this.auth
访问它,怎么回事?如果我们用this.nav
尝试相同的操作,除非我们显式设置实例变量,否则它将不起作用.在构造函数参数中使用private
关键字有什么作用-在类的属性定义以及函数参数中声明私有关键字是否多余?如果它们具有相同的名称,是否可以神奇地将构造函数变量绑定到类属性?
So I'm looking at an ionic 2 project which is using Angular 2 and Typescript and am a bit confused about how member properties are set. Looking at the example below, Angular automatically injects the dependencies in the constructor arguments. In the case of nav, we are explicitly setting the instance member nav to what's being passed in by the constructor. In the case of Firebase auth, we don't explicitly set it to a member variable, but we can still access it via this.auth
in the login method, how come? if we try the same thing with this.nav
it won't work unless we explicitly set the instance variable. What does using the private
keyword do in the constructor parameters do - is it redundant to declare a private keyword in the property definition in the class and also in the function parameters? Is it magically binding constructor variables to class properties if they have the same name?
export class LoginPage {
nav:NavController;
private auth: FirebaseAuth;
constructor(nav:NavController, private auth: FirebaseAuth) {
this.nav = nav; // if we don't do this, the setRoot below in login doesn't do anything
//this.auth = auth; // how come we don't have to set the member variable here and it's still available in the login method
}
login() {
this.auth.login().then(authData =>{
this.nav.setRoot(TabsPage);
});
}
}
推荐答案
注意private auth: FirebaseAuth
中的private
关键字,这是一种缩写语法,用于声明从构造函数参数初始化的类属性.它与:
Notice private
keyword in private auth: FirebaseAuth
, it is shorthand syntax to declare class properties initialized from constructor arguments.It is the same as:
private auth:FirebaseAuth;
constructor(auth: FirebaseAuth) {this.auth = auth;}
这篇关于angular 2打字稿中的成员属性和构造函数的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!