一、事件
<Button text="Sign in" class="submit-button" (tap)="submit()"></Button>
二、数据应用(模型对象)
1.创建模型对象来存储用户数据,例如:在app/shared/user中创建user.ts
export class User {
email: string;
password: string;
}
2.在应用程序app.component.ts中应用要先导入,例如:
import { User } from "./shared/user/user";
export class AppComponent {
user: User;
isLoggingIn = true;
constructor() {
this.user = new User();
}
submit() {
alert("You’re using: " + this.user.email);
}
}
一个新的构造函数中实例化User类的一个实例,当它引导应用程序时,它会调用该函数。
3.页面中应用:
<TextField [(ngModel)]="user.password"></TextField>
三、service(创建服务)
1.创建一个基本的angular服务,在app/shared/user中创建user.service.ts
import { Injectable } from "@angular/core";
import { User } from "./user";
@Injectable()
export class UserService {
register(user: User) {
alert("About to register: " + user.email);
}
}
2.这个服务使用一个方法(eg:register(user:User))来获取您在上一节中创建的User对象的实例。
3.一个新东西是@ injectable。这个decorator表示这个类作为angular的依赖注入机制的候选。现在,只需考虑将@ inectablej添加为您所编写的所有服务的必需约定。
四、service (应用服务)
1.在应用程序app.component.ts中导入服务
import { UserService } from "./shared/user/user.service";
向现有的@Component decorator装饰器添加一个新的提供者属性
@Component({
selector: "my-app",
providers: [UserService],
templateUrl: "./pages/login/login.html",
styleUrls: ["./pages/login/login-common.css", "./pages/login/login.css"]
})
providers数组是您在组件中需要使用的所有angular服务的列表
2.应用UserService服务
constructor(private userService: UserService) {
this.user = new User();
}
这是angular的依赖注入实现的作用。因为在这个组件的providers数组中,注册了UserService作为提供者,当angular看到这个语法时,它会创建一个UserService类的实例,并将该实例传递到组件的构造函数中。
signUp() {
this.userService.register(this.user);
}
五、路由(在routing中使用)
1.app.routing.ts文件是声明应用程序所有路径的列表。例如:
import { LoginComponent } from "./pages/login/login.component";
import { ListComponent } from "./pages/list/list.component";
export const routes = [
{ path: "", component: LoginComponent },
{ path: "list", component: ListComponent }
];
export const navigatableComponents = [
LoginComponent,
ListComponent
];
当您需要添加新的路由时,您需要在app.routing.ts中导入组件,然后将该组件包含在routes和navigatableComponents数组中。
2.在app.module.ts中导入一个NativeScriptRouterModule
模块和在app.routing.ts中刚刚声名的路由
import { NgModule } from "@angular/core";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { AppComponent } from "./app.component";
import { routes, navigatableComponents } from "./app.routing";
@NgModule({
imports: [
NativeScriptModule,
NativeScriptRouterModule,
NativeScriptRouterModule.forRoot(routes)
],
declarations: [
AppComponent,
...navigatableComponents
],
bootstrap: [AppComponent]
})
export class AppModule {}
其中declarations数组的语法: ES2015 spread syntax
B=[2,3] C=[1,...B] 则C=[1,2,3]
六、路由(在Component中使用)
1.首先在Component.ts文件中导入Router
import { Router } from "@angular/router";
2.在构造函数中
constructor(private router: Router, private userService: UserService) {
此处的router和userService一样,angular看到这个语法时,会创建一个Router类的实例,并将该实例传递到组件的构造函数中。
之所有不用将Router添加到Component.ts文件中的provides:[]中,是因为在app.module.ts中导入的NativeScriptRouterModule
中包含了Router
3.应用router
login() {
this.router.navigate(["/list"])
}