1.如何开始
1.创建项目;
- 全局安装angular
npm install -g @angular/cli
复制代码
- 新建项目
ng new angular-tour-of-heroes;
cd angular-tour-of-heroes
//然后输入命令 查看angular版本信息:
ng --version
复制代码
- 开始(监听)项目 (这个命令以后会常用):
ng serve --open;
//恭喜你,现在你已经可以输出自己的“hello,world”了。
复制代码
2.常用命令
1.打开项目
ng serve --open
复制代码
2.创建commponent
ng generate component componentName
复制代码
3.创建service
ng generate service servicenName --module=app
复制代码
4.创建路由
ng generate module app-routing --flat --module=app
复制代码
5.启动或开始
ng serve --open
ng serve --port 0 --open
复制代码
6.发布
ng build --prod --base-href ../GBmono/
复制代码
3.angular组件
Scaffold | Usage |
---|---|
Component | ng g component my-new-componen - 指定目录创建 components/Footer |
Directive | ng g directive my-new-directive |
Pipe | ng g pipe my-new-pipe |
Service | ng g service my-new-service |
class | ng g class my-new-class |
Guard | ng g guard my-new-guard |
Interface | ng g interface my-new-interface |
Enum | ng g enum my-new-enum |
Module | ng g module my-module |
1.创建组件
1.1 ng g component components/header
1.2使用组件
<app-header></app-header>
复制代码
1.3 数据文本绑定
<h1>
{{title}}
</h1>
复制代码
2.绑定 html
this.h="<h2>这是一个 h2 用[innerHTML]来解析</h2>"
<div [innerHTML]="h"></div>
复制代码
3.数据循环*ngFor
<ul>
<li *ngFor="let item of list">
{{item}}
</li>
</ul>
<!-- 循环时设置key -->
<ul>
<li *ngFor="let item of list;let i = index;">
{{item}} --{{i}}
</li>
</ul>
复制代码
4.条件判断*ngIf
<p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p>
<p template="ngIf list.length > 3">这是 ngIF 判断是否显示</p>
复制代码
5.执行事件 (click)="getData()"
<button class="button" (click)="getData()">
点击按钮触发事件
</button>
<button class="button" (click)="setData()">
点击按钮设置数据
</button>
复制代码
getData(){ /*自定义方法获取数据*/
//获取
alert(this.msg);
}
setData(){
//设置值
this.msg='这是设置的值';
}
复制代码
6.绑定属性
<div [id]="id" [title]="msg">调试工具看看我的属性</div>
复制代码
keyUpFn(e){
console.log(e)
}
复制代码
7.双向数据绑定
<input [(ngModel)]="inputValue">
复制代码
7.1.需要引入FormsModule;
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
复制代码
7.2.如果是form中使用ngModule,需要给Input 添加 [ngModuleOptions] = "{standalone:true}"
8.Todolist 功能
<input type="text" [(ngModel)]='username'>
<button (click)='addData()'>增加</button>
<ul>
<li *ngFor="let item of list">
{{item}}
</li>
</ul>
复制代码
export class TodolistComponent implements OnInit {
list:any[];
username:any;
constructor() {}
ngOnInit() {
this.list=[];
this.username='';
}
addData(){
alert(this.username);
this.list.push(this.username);
}
}
复制代码
4.父组件给子组件传值 - @Input
1.父组件调用子组件的时候传入数据
<app-header [msg]="msg"></app-header>
复制代码
2.子组件引入 Input 模块
import { Component, OnInit ,Input } from '@angular/core';
复制代码
3.子组件中 @Input 接收父组件传过来的数据
export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
复制代码
5.@Input 接收父组件传过来的数据也可以在父类中接收子类中使用,@Input其接收值必须是引用传递
father.html
<common-table #appTable [config]="tableConfig"></common-table>
复制代码
basecompentens.ts
@Input() config: any;
复制代码
sun.ts
export class TableComponent extends BaseComponent implements OnInit {
ngOnInit() {
console.log(this.config);
}
}
复制代码
5.子组件中使用父组件的数据
<h2>这是头部组件--{{msg}}</h2>
复制代码
6.父子组件传值的方式让子组件执行父组件的方法
6.1父组件定义方法
run(){
alert("我是父组件方法!")
}
复制代码
6.2调用子组件传入当前方法
<app-header [msg]="msg" [run]="run"></app-header>
复制代码
6.3. 子组件接收父组件传过来的方法
import { Component, OnInit ,Input } from '@angular/core';
export class HeaderComponent implements OnInit {
@Input() msg:string
@Input() run:any;
constructor() { }
}
复制代码
6.4. 子组件使用父组件的方法。
export class HeaderComponent implements OnInit {
@Input() msg:string;
@Input() run:any;
constructor() { }
ngOnInit() {
this.run(); /*子组件调用父组件的 run 方法*/
}
}
复制代码
7.子组件通过@Output执行父组件的方法
7.1 子组件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
复制代码
7.2 子组件中实例化 EventEmitter
@Output() private outer=new EventEmitter<string>();
复制代码
7.3 子组件通过 EventEmitter 对象 outer 实例广播数据
sendParent(){
// alert('zhixing');
this.outer.emit('msg from child')
}
复制代码
7.4 父组件调用子组件的时候,定义接收事件 , outer 就是子组件的 EventEmitter 对象 outer
<app-header (outer)="runParent($event)"></app-header>
复制代码
7.5 父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据
//接收子组件传递过来的数据
runParent(msg:string){
alert(msg);
}
复制代码
8.父组件通过局部变量获取子组件的引用,主动获取子组件的数据和方法(一)
8.1定义 footer 组件
export class FooterComponent implements OnInit {
public msg:string;
constructor() {
}
ngOnInit() {
}
footerRun(){
alert('这是 footer 子组件的 Run 方法');
}
}
复制代码
8.2.父组件调用子组件的时候给子组件起个名字
<app-footer #footer></app-footer>
复制代码
8.3.直接获取执行子组件的方法
<button (click)='footer.footerRun()'>获取子组件的数据</button>
复制代码
9.父组件通过局部变量获取子组件的引用,通过 ViewChild主动获取子组件的数据和方法
9.1.调用子组件给子组件定义一个名称
<app-footer #footerChild></app-footer>
复制代码
9.2 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
复制代码
9.3.ViewChild 和刚才的子组件关联起来
@ViewChild('footerChild') footer;
复制代码
9.4.调用子组件
run(){
this.footer.footerRun();
}
复制代码
10.全局对象注册
10.1 创建typings.d.ts文件
typings.d.ts
declare var $: any;
declare var Config: any;
复制代码
10.2 在html引入配置文件
<script type="text/javascript" src="./assets/config.js"></script>
<script type="text/javascript" src="./assets/jq.js"></script>
复制代码
10.3 在html引入配置文件
app.moudule.ts
//直接使用暴露对象
console.log($,jq);
复制代码
5.路由
1.创建一个简单路由;
- Add the AppRoutingModule
ng generate module app-routing --flat --module=app;
复制代码
注释:--flat 把这个文件放进了 src/app 中,而不是单独的目录中。--module=app 告诉 CLI 把它注册到 AppModule 的 imports 数组中 app-routing
import { RouterModule, Routes } from '@angular/router';
import { MyCompComponent } from './my-comp/my-comp.component';
import { SiginComponent } from './sigin/sigin.component';
import { HomeModuleComponent } from './home-module/home-module.component';
const appRoutes: Routes = [
{
path: '',
redirectTo: '/sigin',
pathMatch: 'full'// 针对控的path 必须指定full;
},
{
path: 'sigin',
component: SiginComponent,
},
{
path: 'index',
component: MyCompComponent,
},
{
path: 'home',
component: HomeModuleComponent,
}
];
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(appRoutes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
复制代码
2.所有在路由中使用的组件必须在app.module中注册;
app.module.ts
import { MyCompComponent } from './my-comp/my-comp.component';
import { HomeModuleComponent } from './home-module/home-module.component';
import { SiginComponent } from './sigin/sigin.component';
@NgModule({
declarations: [
AppComponent,
SiginComponent,
MyCompComponent,
HomeModuleComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
NgZorroAntdModule,
ReactiveFormsModule
],
providers: [{ provide: NZ_I18N, useValue: zh_CN }],
bootstrap: [AppComponent]
})
复制代码
3.路由默认选中路由
Angular routerLinkActive 设置 routerLink 默认选中路由
<h1>
<a routerLink="/home" routerLinkActive="active">首页</a>
<a routerLink="/news" routerLinkActive="active">新闻</a>
</h1>
<style>
.active{
color:red;
}
<style>
复制代码
4.动态路由使用;
app-routing.module.ts
const routes: Routes = [
{
path: 'home',
component:HomeComponent
},
{
path: 'news',
component:NewsComponent
},
{
path: 'newscontent/:aid', /*配置动态路由*/
component:NewscontentComponent
}
,{ /*匹配不到路由的时候加载的组件*/
path: '**', /*任意的路由*/
// component:HomeComponent
redirectTo:'home'
}
];
复制代码
newscontent.component.ts
ngOnInit() {
//获取动态路由
// console.log(this.route.params.value.aid); //错误的写法
//获取动态路由的传值
this.route.params.subscribe(function(data){
console.log(data.aid);
})
}
复制代码
5.路由的js跳转
5.1.引入
import { Router } from '@angular/router';
复制代码
5.2.初始化
export class HomeComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
goNews(){
// this.router.navigate(['/news', hero.id]);
this.router.navigate(['/news']);
}
}
复制代码
5.3.路由跳转
this.router.navigate(['/news', hero.id]);
复制代码
5.4 路由的js跳转get传值;
//引入 NavigationExtras
import { Router ,NavigationExtras,ActivatedRoute} from '@angular/router';
//定义一个 goNewsContent 方法执行跳转, 用 NavigationExtras 配置传参
goNewsContent(){
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': '123' },
fragment: 'anchor'
};
this.router.navigate(['/news'],navigationExtras);
}
//获取 get 传值
constructor(private route: ActivatedRoute) {
console.log(this.route.queryParams);
}
复制代码
6.父子路由
6.1.创建组件引入组件
import { NewsaddComponent } from './components/newsadd/newsadd.component';
import { NewslistComponent } from './components/newslist/newslist.component';
复制代码
6.2.配置路由
{
path: 'news',
component:NewsComponent,
children: [
{
path:'newslist',
component:NewslistComponent
},
{
path:'newsadd',
component:NewsaddComponent
}
]
}
复制代码
6.3.父组件中定义 router-outlet
<router-outlet></router-outlet>
复制代码
6.4 项目中各模块间路由引用(子模块路由配置);
6.4.1.项目中的list模块
;6.4.2.对list模块进行路由管理;
list-router.module路由文件如下;
6.4.3.我们对list模块进行了路由管理,当我们需要在其他模块访问到我们List模块中的组件时,我们需要导出我们在list.module文件导出定义的组件;
6.4.4.定义好list模块里面的路由,我们还需要将list模块路由配置到根路由上,如图配置
app-routing.module
我们访问list模块时就能加载list模块中定义的路由了
6.路由钩子
6.1.CanActivate
import { ngModule, Injectable } from '@angular/core';
import { RouterModule, Routes, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate } from '@angular/router';
import {Observable} from 'rxjs';
@Injectable()
class CanActivateTeam implements CanActivate {
constructor(private router:Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
console.og(state);
console.og(route);
if(state.url !== '/signin'){
return false;
}
if(state.url !== '/signin'){
//return false;
this.router.navigateByUrl('/signin')
}
return true; // 任何路由都放行;
}
}
const routes: Routes = [
{
path: 'core',
component: FooterComponent,
canActivate: [CanActivateTeam]
},
{
path: 'index',
component: FooterComponent,
canActivate: [CanActivateTeam]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers:[CanActivateTeam]
})
复制代码
7.服务(service)
6.1安装
ng g service my-new-service
//创建到指定目录下面
ng g service services/storage
复制代码
- app.module.ts 里面引入创建的服务
//1.app.module.ts 里面引入创建的服务
import { StorageService } from './services/storage.service';
//2. NgModule 里面的 providers 里面依赖注入服务
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent,
TodolistComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }
复制代码
- 使用的页面引入服务,注册服务
//引入服务
import { StorageService } from '../../services/storage.service';
//constuctor
constructor(private storage: StorageService) { };
//使用
addData(){
// alert(this.username);
this.list.push(this.username);
this.storage.set('todolist',this.list);
}
removerData(key){
console.log(key);
this.list.splice(key,1);
this.storage.set('todolist',this.list);
}
复制代码
6.2.使用
6.2.1.引入 HttpModule、JsonpModule 普通的 HTTP 调用并不需要用到 JsonpModule,不过稍后我们就会演示对 JSONP 的支持, 所以现在就加载它,免得再回来改浪费时间
import { HttpModule, JsonpModule } from '@angular/http';
复制代码
6.2.2.HttpModule 、 JsonpModule依赖注入
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NewsComponent,
NewscontentComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
AppRoutingModule
],
providers: [StorageService,NewsService],
bootstrap: [AppComponent]
})
export class AppModule { }
复制代码
6.2.3.app.module.ts 引入并且依赖注入完成以后, 在需要用到的地方执行下面操作
6.3.使用 Http、 Jsonp:
6.3.1.在需要请求数据的地方引入 Http
import {Http,Jsonp} from "@angular/http";
复制代码
6.3.2构造函数内申明:
constructor(private http:Http,private jsonp:Jsonp) { }
复制代码
6.3.3对应的方法内使用 http 请求数据
//get
this.http.get("http://www.phonegap100.com/appapi.php?a=getPortalList&ca
tid=20&page=1")
.subscribe(
function(data){
console.log(data);
},function(err){
console.log('失败');
}
);
//jsonp
this.jsonp.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK")
.subscribe(
function(data){
console.log(data);
},function(err){
console.log('失败');
}
);
复制代码
6.4.使用 Post;
6.4.1 引入 Headers 、 Http 模块
import {Http,Jsonp,Headers} from "@angular/http";
复制代码
6.4.2 实例化 Headers
private headers = new Headers({'Content-Type': 'application/json'});
复制代码
6.4.3.post 提交数据
this.http.post('http://localhost:8008/api/test',
JSON.stringify({username: 'admin'}), {headers:this.headers})
// .toPromise()
.subscribe(function(res){
console.log(res.json());
});
复制代码
7.rxjx -- 中间件
1.Observable
this.http 返回的是Observable对象,rxjx就是处理Observable的,类似于promise, Observable;
this.http.get("http://www.phonegap100.com/appapi.php?a=getPortalList&ca
tid=20&page=1")
.subscribe(
function(data){
console.log(data);
},function(err){
console.log('失败');
}
);
复制代码
2.导入rxjs;
import { tap,catchError } from 'rxjs/operator';
import { Observable, of } from 'rxjs';
复制代码
3.使用
private errorHandler(error:any) :Observable<any>{
console.log(error);
return of("") // 返回一个observable
}
this.http.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1")
.pipe(
//Observable
tap(res=>{
console.log(res);
}),
catchError(this.errorHandler); //公共处理异常的方法;
)
复制代码