Angular 入门

2018-10-05  本文已影响0人  地瓜粉丝

Angular介绍

开源Web前端框架,被Google收购。

Angular 1.X 和 Angular 2.X 系列不一样。同时维护 <br />

作用:<br />

x

<br />

特点:

开发工具:Visual Studio Code

Angular安装、创建项目、目录结构、组件、服务

1. 安装最新版Node.js;安装成功后,命令提示符下输入校验:


C:\Users\reid>node -v

v8.11.1

C:\Users\reid>npm -v

5.6.0

2. 全局安装Angular CLI


npm install -g @angular/cli

--国内angular 镜像安装

npm install -g cnpm --registry=https://registry.npm.taobao.org

cnpm install -g @angular/cli

3. 创建项目


<article class="markdown-body" id="preview" data-open-title="Hide Preview" data-closed-title="Show Preview" style="text-size-adjust: 100%; color: rgb(36, 41, 46); font-family: -apple-system, BlinkMacSystemFont, 微软雅黑, &quot;PingFang SC&quot;, Helvetica, Arial, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, SimSun, 宋体, Heiti, 黑体, sans-serif; font-size: 14px; line-height: 1.5; word-wrap: break-word; min-width: 256px; max-width: 978px; margin: 0px auto; padding: 20px 20px 602px; tab-size: 4;">

*   *   [Angular介绍](#angular介绍)
    *   [Angular安装、创建项目、目录结构、组件、服务](#angular安装-创建项目-目录结构-组件-服务)
    *   [创建组件、绑定数据、绑定属性、数据循环、条件判断、事件、表单处理、双向数据绑定](#创建组件-绑定数据-绑定属性-数据循环-条件判断-事件-表单处理-双向数据绑定)
        *   *   [1\. 创建组件](#1-创建组件)
            *   [2\. 绑定数据](#2-绑定数据)
            *   [3\. 数据循环 *ngFor](#3-数据循环-ngfor)
            *   [4\. 条件判断](#4-条件判断)
            *   [5\. 执行事件](#5-执行事件)
            *   [6\. 绑定属性](#6-绑定属性)
            *   [7\. 表单处理](#7-表单处理)
            *   [8\. 双向数据绑定](#8-双向数据绑定)
    *   [get post jsonp请求数据](#get-post-jsonp请求数据)
        *   *   [app.module.ts注册HTPP JSONP服务](#appmodulets注册htpp-jsonp服务)
    *   [创建使用服务](#创建使用服务)
        *   *   *   [创建服务](#创建服务)
                *   [app.moduel.ts引入服务](#appmoduelts引入服务)
                *   [使用页面引入、注册服务](#使用页面引入-注册服务)
                *   [使用](#使用)
    *   [父子组件传值 @Input @Output @ViewChild](#父子组件传值-input-output-viewchild)
    *   [路由](#路由)

</article>

## Angular介绍
开源Web前端框架,被Google收购。
Angular 1.X 和 Angular 2.X 系列不一样。同时维护 
作用:
- APP和微信上的单页面应用
- 借助Ionic、React Native开发跨平台的原生APP
- 可以开发桌面应用,创建能在桌面环境下安装的应用,横跨Mac、Windows和Linux
特点:
- 组件化
- 模块化
- 开发单页面应用 
开发工具:Visual Studio Code

## Angular安装、创建项目、目录结构、组件、服务
1. 安装最新版Node.js;安装成功后,命令提示符下输入校验:

C:\Users\reid>node -v
v8.11.1

C:\Users\reid>npm -v
5.6.0

2. 全局安装Angular CLI

npm install -g @angular/cli
--国内angular 镜像安装
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install -g @angular/cli

3. 创建项目

ng new my-app //创建项目
cd my-app
cnpm install //安装依赖
ng serve --open //启动服务

4. 项目目录结构分析
    1. e2e 端到端的测试文件
    2. node_modules Node.js创建了该文件夹,并且把package.json中列举的所有第三方模块都放在该文件夹下。
    3. src  项目所有的文件都得放在SRC下面
    4. .editorconfig    编辑器看的简单的配置文件,确保每个人都有基本的编辑器配置
    5. .gitignore   Git配置文件,确保有些文件不会提交到Git中
    6. angular.json 
    7. my-app.code-workspace
    8. package-lock.json
    9. package.json npm 配置文件,其中列出了项目使用到的第三方依赖包。 你还可以在这里添加自己的自定义脚本。
    10. README.md   项目基础文件
    11. tsconfig.json   TypeScript编译器的基础配置
    12. tslint.json 给 TSLint 和 Codelyzer 用的配置信息,当运行 `ng lint` 时会用到。Lint 功能可以帮你保持代码风格的统一
    <br />
    1. SRC目录分析
        1. app/app.component.{ts,html,css,spec.ts} 组件 使用 HTML 模板、 CSS 样式和单元测试定义 AppComponent 组件。 它是根组件,随着应用的成长它会成为一棵组件树的根节点。
        2. app/app.module.ts 定义 AppModule,这个根模块会告诉Angular 如何组装该应用。 目前,它只声明了 AppComponent。稍后它还会声明更多组件。
        3. assets/* 静态资源 这个文件夹下你可以放图片等任何东西,在构建应用时,它们全都会拷贝到发布包中。
        4. environments/* 这个文件夹中包括为各个目标环境准备的文件,它们导出了一些应用中要用到的配置变量。 这些文件会在构建应用时被替换。比如你可能在产品环境中使用不同的 API端点地址,或使用不同的统计 Token 参数。甚至使用一些模拟服务。 所有这些, CLI都替你考虑到了。
        5. favicon.ico 每个网站都希望自己在书签栏中能好看一点。 请把它换成你自己的图标。index.html 这是别人访问你的网站是看到的主页面的HTML 文件。大多数情况下你都不用编辑它。 在构建应用时, CLI 会自动把所有 js和 css 文件添加进去,所以你不必在这里手动添加任何 <script> 或 <link> 标签。
        6. main.ts 这是应用的主要入口点。 使用 JIT compiler编译器编译本应用,并启动应用的根模块AppModule,使其运行在浏览器中。 你还可以使用 AOT compiler 编译器,而不用修改任何代码 —— 只要给 ng build 或 ngserve 传入 --aot 参数就可以了。
        7. polyfills.ts 不同的浏览器对 Web 标准的支持程度也不同。 填充库(polyfill)能帮我们把这些不同点进行标准化。 你只要使用core-js 和 zone.js 通常就够了,不过你也可以查看浏览器支持指南以了解更多信息。
        8. styles.css 这里是你的全局样式。 大多数情况下,你会希望在组件中使用局部样式,以利于维护,不过那些会影响你整个应用的样式你还是需要集中存放在这里。
        9. test.ts 这是单元测试的主要入口点。 它有一些你不熟悉的自定义配置,不过你并不需要编辑这里的任何东西。
        10. tsconfig.{app|spec}.json TypeScript 编译器的配置文件。
        11. tsconfig.app.json 是为 Angular 应用准备的,而 tsconfig.spec.json 是为单元测试准备的。
    13. AppModule组件分析
app.module.ts
import { AppComponent } from './app.component'; /*根组件*/
/*@NgModule 装饰器将 AppModule 标记为 Angular 模块类(也叫 NgModule 类)。
@NgModule 接受一个元数据对象,告诉 Angular 如何编译和启动应用。 */
@NgModule({
declarations: [ /*引入当前项目运行的的组件*/
AppComponent
],
imports: [ /*引入当前模块运行依赖的其他模块*/
BrowserModule,
FormsModule,
HttpModule
],
providers: [], /*定义的服务 回头放在这个里面*/
bootstrap: [AppComponent] /* 指定应用的主视图(称为根组件) 通过引导根 AppModule 来启动
应用 ,这里一般写的是根组件*/
})
/*根模块不需要导出任何东西, 因为其它组件不需要导入根模块。 但是一定要写*/
export class AppModule { }


## 创建组件、绑定数据、绑定属性、数据循环、条件判断、事件、表单处理、双向数据绑定
#### 1. 创建组件
Scaffold | Usage
---|---
componnet | `ng g component my-new-component  指定目录创建 : ng g component 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`
Mudule|`ng g module my-module`
#### 2. 绑定数据

{{title}}
this.h="<h2>这是一个 h2 用[innerHTML]来解析</h2>
<div [innerHTML]="h"></div>

#### 3. 数据循环 *ngFor

<ul>
<li *ngFor="let item of list">
{{item}}
</li>
</ul>

<ul>
<li *ngFor="let item of list;let i = index;">
{{item}} --{{i}}
</li>
</ul>

<ul>
<li template="ngFor let item of list">
{{item}}
</li>
</ul>

#### 4. 条件判断

<p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p>
<p template="ngIf list.length > 3">这是 ngIF 判断是否显示</p>

#### 5. 执行事件

<button class="button" (click)="getData()">
点击按钮触发事件
</button>
<button class="button" (click)="setData()">
点击按钮设置数据
</button>


getData(){ /自定义方法获取数据/
//获取
alert(this.msg);
}
setData(){
//设置值this.msg='这是设置的值';
}

#### 6. 绑定属性

动态设置id 和title
<div [id]="id" [title]="msg">调试工具看看我的属性</div>

#### 7. 表单处理

<input type="text" (keyup)="keyUpFn($event)"/>
keyUpFn(e){
console.log(e)
}

#### 8. 双向数据绑定

需要引入:FormsModule
修改数据直接相互影响

<input [(ngModel)]="inputValue">

import { FormsModule } from '@angular/forms';

@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

<input type="text" [(ngModel)]="inputValue"/> --双向数绑定

{{inputValue}} --读取值

## get post jsonp请求数据
#### app.module.ts注册HTPP JSONP服务
   1. 引入HttpModule、JsonpModule
   import { HttpModule, JsonpModule } from '@angular/http'
   2. HttpModule 、 JsonpModule 依赖注入
   @NgModule({
       declarations: [
           AppComponent,
           HomeComponent,
           NewsComponent,
           NewscontentComponent
       ],
       imports: [
           BrowserModule,
           FormsModule,
           HttpModule,
           JsonpModule,
           AppRoutingModule
       ],
       providers: [StorageService,NewsService],
       bootstrap: [AppComponent]
   })
   export class AppModule { }
   3. 通过Http、Jsonp请求数据GET 
   --需要请求的页面引入
   import {Http,Jsonp} from "@angular/http";
   --构造方法
   constructor(private http:Http,private jsonp:Jsonp) { }
   --请求方法 HTTP GET
   this.http.get("https://services.odata.org/v4/(S(hxv25dolqxu3jayczcr4h0rt))/TripPinServiceRW/People?$top=2").subscribe(
       function(data){
           console.log(data);
       },function(err){
           console.log('失败');
       }
   );
   --请求方法 JSONP  GET 增加&callback=JSONP_CALLBACK参数
   this.jsonp.get("https://services.odata.org/v4/(S(hxv25dolqxu3jayczcr4h0rt))/TripPinServiceRW/People?$top=2&callback=JSONP_CALLBACK").subscribe(
       function(data){
           console.log(data);
       },function(err){
           console.log('失败');
       }
   );
   
   4. 通过Http、Jsonp请求数据POST
   -- 引入Http、Headers
   import {Http,Jsonp,Headers} from "@angular/http";
   -- 实例化Headers
   private headers = new Headers({'Content-Type': 'application/json'});
   -- 提交数据
   this.http.post('http://localhost:8008/api/test',
                   JSON.stringify({username: 'admin'}), 
                   {headers:this.headers})
                   // .toPromise()
                   .subscribe(function(res){
                       console.log(res.json());
                   });
   5. 使用RxJS
   -- 引入Http 、 Jsonp、 RxJs 模块
   import {Http,Jsonp} from "@angular/http";
   import {Observable} from "rxjs";
   import "rxjs/Rx";
   
   --构造函数内声明
   constructor(private http:Http,private jsonp:Jsonp) { }
   --get 请求
   this.http.get("https://services.odata.org/v4/(S(hxv25dolqxu3jayczcr4h0rt))/TripPinServiceRW/People?$top=2").map(res => res.json())
                   .subscribe(
                       function(data){
                           console.log(data);
                       }
                   );
   --Jsonp请求&callback=JSONP_CALLBACK
   this.jsonp.get("https://services.odata.org/v4/(S(hxv25dolqxu3jayczcr4h0rt))/TripPinServiceRW/People?$top=2&callback=JSONP_CALLBACK")
       .map(res => res.json()).subscribe(
            function(data){
                console.log(data);
            }
           );
http.get 方法中返回一个 Observable 对象,我们之后调用 RxJS 的 map 操作符对返回的数据做处理。

## 创建使用服务
##### 创建服务

ng g service my-new-service
创建到指定目录下面
ng g service services/storage

##### app.moduel.ts引入服务

--app.module.ts
import { StorageService } from './services/storage.service';
-- 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';

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);
}

## 父子组件传值 @Input @Output @ViewChild
1. 父组件给子组件传值

父组件调用子组件的时候传入数据
<app-header [msg]="msg"></app-header>

  1. 子组件引入 Input 模块
    import { Component, OnInit ,Input } from '@angular/core';
  2. 子组件中 @Input 接收父组件传过来的数据export class HeaderComponent implements OnInit {
    @Input() msg:string
    constructor() { }
    ngOnInit() {
    }
    }
  3. 子组件中使用父组件的数据
    <h2>这是头部组件--{{msg}}</h2>
2. 父组件传值的方式让子组件执行父组件方法

将方法名传入,后执行。

  1. 父组件定义方法
    run(){
    alert('这是父组件的 run 方法');
    }
    2.调用子组件传入当前方法
    <app-header [msg]="msg" [run]="run"></app-header>3. --子组件接收父组件传过来的方法
    --引入模块
    import { Component, OnInit ,Input } from '@angular/core';
    --定义接收变量
    @Input() run:any;
    --完整代码
    export class HeaderComponent implements OnInit {
    @Input() msg:string
    @Input() run:any;
    constructor() { }
    }
  2. 子组件使用父组件的方法。
    export class HeaderComponent implements OnInit {
    @Input() msg:string;
    @Input() run:any;
    constructor() { }
    ngOnInit() {
    this.run(); /子组件调用父组件的 run 方法/
    }
    }
3. 子组件通过@Output执行父组件方法

EventEmitter:事件触发器 emit:发出

  1. 子组件引入 Output 和 EventEmitter
    import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';

2.子组件中实例化 EventEmitter
@Output() private outer=new EventEmitter<string>();
/用 EventEmitter 和 output 装饰器配合使用 <string>指定类型变量/

  1. 子组件通过 EventEmitter 对象 outer 实例广播数据
    sendParent(){
    // alert('zhixing');
    this.outer.emit('msg from child')
    }

4.父组件调用子组件的时候,定义接收事件 , outer 就是子组件的 EventEmitter 对象 outer
<app-header (outer)="runParent($event)"></app-header>
将 outer 与父组件方法 runParent 绑定,执行outer.emit即执行runParent
5.父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据//接收子组件传递过来的数据
runParent(msg:string){
alert(msg);
}

4. 父组件通过局部变量获取子组件的引用,主动获取子组件的数据和方法(一)
  1. 定义 footer 组件
    export class FooterComponent implements OnInit {
    public msg:string;
    constructor() {
    }
    ngOnInit() {
    }
    footerRun(){
    alert('这是 footer 子组件的 Run 方法');
    }
    }
  2. 父组件调用子组件的时候给子组件起个名字
    <app-footer #footer></app-footer>3. 直接获取执行子组件的方法
    <button (click)='footer.footerRun()'>获取子组件的数据</button>
5. 父组件通过 ViewChild 主动获取子组件的数据和方法

1.调用子组件给子组件定义一个名称
<app-footer #footerChild></app-footer>

  1. 引入 ViewChild
    import { Component, OnInit ,ViewChild} from '@angular/core';
  2. ViewChild 和页面引入的子组件关联起来。别名一致
    @ViewChild('footerChild') footer;
    4.调用子组件
    run(){
    this.footer.footerRun();
    }
## 路由
1. 创建一个配置好路由的项目

1.创建项目
ng new demo02 –-routing

  1. 创建需要的组件
    ng g component home
    ng g component news
    ng g component newscontent
  2. 找到 app-routing.module.ts 配置路由
    引入组件
    import { HomeComponent } from './home/home.component';
    import { NewsComponent } from './news/news.component';
    import { NewscontentComponent } from './newscontent/newscontent.component';
    配置路由
    const routes: Routes = [
    {path: 'home', component: HomeComponent},
    {path: 'news', component: NewsComponent},
    {path: 'newscontent/:id', component: NewscontentComponent},
    {
    path: '',
    redirectTo: '/home',pathMatch: 'full'
    }
    ];
  3. 找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由
    <h1>
    <a routerLink="/home">首页</a>
    <a routerLink="/news">新闻</a>
    </h1>
    <router-outlet></router-outlet>
2. 给没有路由的项目配置路由
  1. 新建组件
    ng g component home
    ng g component news
    ng g component newscontent

  2. 新建 app-routing.module.ts ,app-routing.module.ts 中引入模块
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';

  3. app-routing.module.ts 中引入组件
    import { HomeComponent } from './home/home.component';
    import { NewsComponent } from './news/news.component';
    import { NewscontentComponent } from './newscontent/newscontent.component';

  4. app-routing.module.ts 中配置组件
    const routes: Routes = [
    {path: 'home', component: HomeComponent},
    {path: 'news', component: NewsComponent},
    {path: 'newscontent/:id', component: NewscontentComponent},
    {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
    }
    ];

  5. app-routing.module.ts 中配置模块 暴露模块
    @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
    })
    export class AppRoutingModule { }

  6. 在 app.module.ts 引入刚才定义的路由
    import { AppRoutingModule } from './app-routing.module';

7.app.module.ts 里面的 import 注册这个路由模块
imports: [
BrowserModule,
AppRoutingModule
]
8.找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由<h1>
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
</h1>
<router-outlet></router-outlet>

3. Angular routerLink 页面跳转 默认跳转路由

<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
//刚进来路由为空跳转的路由
{
path:'',
redirectTo:'home',
pathMatch:"full"
}
//匹配不到路由的时候加载的组件 或者跳转的路由
{
path: '', /任意的路由/
// component:HomeComponent
redirectTo:'home'
}

4. Angular routerLinkActive 设置 routerLink 选中样式

<h1>
<a routerLink="/home" routerLinkActive="active">首页</a>
<a routerLink="/news" routerLinkActive="active">新闻</a>
</h1>
-- css 样式 类
.active{
color:red;
}

5. 路由的动态传值.

1.配置动态路由
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
2.获取动态路由的值
import { Router, ActivatedRoute, Params } from '@angular/router';
constructor( private route: ActivatedRoute) {}
ngOnInit() {
console.log(this.route.params);//
this.route.params.subscribe(data=>this.id=data.id);
}

6. 路由的 js 跳转.
  1. 引入
    import { Router } from '@angular/router';
    2.初始化
    export class HomeComponent implements OnInit {
    constructor(private router: Router) {
    }
    ngOnInit() {
    }
    goNews(){
    // this.router.navigate(['/news', hero.id]);
    this.router.navigate(['/news']);
    }
    }
    3.路由跳转
    this.router.navigate(['/news', hero.id]);
7. 路由的 js 跳转 get 传值
  1. 引入 NavigationExtras
    import { Router ,NavigationExtras,ActivatedRoute } from '@angular/router';
    2.定义一个 goNewsContent 方法执行跳转, 用 NavigationExtras 配置传参。
    goNewsContent {
    let navigationExtras: NavigationExtras = {
    queryParams: { 'session_id': '123' },
    fragment: 'anchor'
    };
    this.router.navigate(['/news'],navigationExtras);
    }
    3.获取 get 传值
    constructor(private route: ActivatedRoute) {
    console.log(this.route.queryParams);
    }
8. 父子路由

创建组件引入组件
import { NewsaddComponent } from './components/newsadd/newsadd.component';
import { NewslistComponent } from './components/newslist/newslist.component';

  1. 配置路由
    {
    path: 'news',
    component:NewsComponent,
    children: [
    {
    path:'newslist',
    component:NewslistComponent
    },
    {
    path:'newsadd',
    component:NewsaddComponent
    }
    ]
    }
  2. 父组件中定义 router-outlet
    <router-outlet></router-outlet>
上一篇下一篇

猜你喜欢

热点阅读