入职15天,Angular2 小记!

时间:2023-03-09 03:24:57
入职15天,Angular2 小记!

ng 配置
@ngModule({
imports: [ BrowserModule ], //导入模块
declarations: [ AppComponent ], //导入组件

providers: [ ] //导入服务(service)


})

在app主模块下

app.module 引入大模块的集合
====》
import {SmartadminLayoutModule} from "./shared/layout/layout.module";

app.routing 引入/定义 根路由

定义一个product的模块
(product模块下的组件所依赖的辅助模块,需要在导入到product.module)

1.创建product模块和路由
ng g module +product/product --routing --flat
2.在+product下创建组件, 如:category
ng g component +product/+category/category --flat
product.module会自动引入该组件
3.路由跳转 product-routing
一 引入category组件
二 定义category路由
{
path: 'category',
component: 'CategoryComponent',
data: { pageTitle: '分类' } //传入数据
}
4.组件的用法 category
一 调用API数据
先创建一个product.service

在里面定义一个获取API数据的方法
getCategories(): Observable<any> {
return this.http.JsonApi('/product/category.json');
};

在product.module中引入该服务
import { ProductService } from './product.service';
provides: [ ProductService ] //依赖注入

在category.component.ts中引入该服务
import { ProductService } from './product.service';
实例化该服务
constructor(
private productService: ProductService
){ }
ajax调用, 获取数据
this.productService.getCategories()