前端知識點總結——Angular

前端知識點總結——Angular

1、Angular概述html

基於命令行的開發方式?前端

①hot reload
②編譯工做
③集成了webpack打包工具
。。。。

angular.cn 中文
angular.io 正式官網
angular.cn/guide/styleguide 風格指南vue

一、what?webpack

angular是一個Google推出的js框架,是以模塊爲基本單位,模塊又能夠包含組件、指令、過濾器。。

1.1 版本問題
    angular angular2.0之後全部的版本統稱爲angular
    (當前學習ng4.0)

    angular.js angular1.* 統稱爲angular.js
    (http://www.runoob.com/angularjs/angularjs-tutorial.html)

1.2 版本之間的區別
    ①新版本是有組件的概念的
    ②老版本是$scope和controller爲主
    ③angular引入了rxjs
    ④angular採用ts(typescript是es6的超集,是由微軟和谷歌) ts是一種強類型檢查機制的語言
    ⑤angular可讀性、提升了代碼的複用率、維護成本變低。。。

二、wheregit

可使用支持angular的Ionic框架來實現移動端的開發,直接使用angular來實現pc端的開發

    實現操做比較頻繁的SPA

三、whyangularjs

①遵循w3c所推出的webComponent標準(組件化)
②代碼具備更好的可讀性和可維護性、
③引入了更多的高效率的工具 ,好比rxjs\immutable.js。。。, 讓代碼的編譯、部署更簡單
④ts --》 健壯

四、howes6

angular的開發總體框架,是有8大組成部分構成

搭建環境的方式:
方式1:
    ①下載quickstart-master.zip壓縮包
    https://github.com/angular/quickstart download
    或者 直接拷貝老師提供的壓縮包
    ②解壓縮 壓縮包,進入對應的目錄中
    執行npm install 安裝項目所須要用到的依賴
    ③npm start 啓動開發服務器

方式2:
    Angular CLI是一個命令行界面工具,它能夠建立項目、
    添加文件以及執行一大堆開發任務,好比測試、打包和發佈。
    //安裝基於angular的命令工具
    npm install -g @angular/cli
    //建立一個有着ng模板的項目
    ng new my-app
    //進入當前目錄下的my-app
    cd my-app
    //啓動開發服務器
    ng serve --open

2、Angular模板項目的啓動流程

index.html

main.js (main.ts)-->啓動一個模塊 AppModule

app/app.module.ts ---> 啓動一個組件 app/app.component.ts

Hello Angular

3、完成組件的建立和使用

一、建立組件和使用組件
    ①建立文件 app/test/test.component.ts
    ②將類裝飾成一個組件類
        import {Component} from '@angular/core'
    
        @Component({
            selector:'test',
            template:`<h1>it is a test</h1>`
        })

        export class Demo01Component{
        }
    ③使用組件
        ①到模塊中聲明
            app.module.ts中,
            import {TestComponent} from './test/test.component'

            @NgModule({
                declarations:[TestComponent]
            })
        ②<test></test>

    練習:(16:50 - 17:00)
        demo02/demo02.component.ts
        組件中渲染一個無序列表(5個列表)

        將組件渲染AppComponent

4、Angular中常見的指令

一、循環指令
Vue :  <any v-for="tmp in list"></any>

Angular: 
        語法:
   <any *ngFor="let tmp of list"></any>
   <any *ngFor="let tmp of list;let myIndex=index"></any>

二、選擇指令
Vue: <any v-if="表達式"></any>
angular:
        <any *ngIf="表達式"></any>

5、常見指令

指令和組件的關係:github

組件就是一個帶有模板的指令!!!

一、多重分支判斷web

vue 
    v-if
    v-else-if
    v-else

<div [ngSwitch]="answer">
    <p *ngSwitchCase="'a'"></p>
    <p *ngSwitchDefault></p>
</div>

二、屬性綁定typescript

Vue:
    <img v-bind:src="imgUrl"/>
    <img :src="imgUrl"/>
    <button :class="{myHightlight:true}"></button>
    <h1 :style="{backgroundColor:myBG}"></h1>

Angular:
    <img [src]="imgUrl"/>
    <button [ngClass]="{myHightlight:true}"></button>
    <h1 [ngStyle]="{backgroundColor:myBG}">
    </h1>

三、事件綁定

Vue
    <button v-on:click="handleClick"></button>
    <button @click="handleClick"></button>
Angular
    語法:
    <any (eventName)="eventHandler()"></any>
    舉例:
    <button (click)="handleClick()"></button>

四、雙向數據綁定

Vue:
    <input v-model="addr"/>
Angular:
    <input [(ngModel)]="addr"/>

依賴注入:
    將依賴的東西注入到指定的地方,讓依賴可被使用
    舉例:AppModule依賴於FormsModule,
    只須要在AppModule的imports數組寫上FormsModule名稱
    就可使用FormsModule所提供的東西。
    好處:解耦,下降了耦合度


Angular中若是想要監聽雙向數據綁定數據的變化,提供一個事件 ngModelChange

注意事項:
①Angular中若是要想使用雙向數據綁定,就必須指定模塊依賴於FormsModule
②使用ngModelChange事件時,經過$event去傳遞用戶當前所輸入的信息
    (ngModelChange)="handleChange($event)"

內置的指令:

*ngFor
*ngIf
*ngSwitchCase
*ngSwitchDefault
ngSwitch
[]
()
[(ngModel)]
{{}}

五、自定義指令

Vue中自定義指令:
    Vue.directive('change',{
        bind:function(el,binding){},
        update:function(){},
        unbind:function(){}
    });
    v-change
Angular中指令建立和使用

5.1 建立
    import {Directive}    from '@angular/core'

    @Directive({
        selector:'[test]'
    })

    export class TestDirective{
    }

5.2 使用
    ①到模塊中聲明
        app.module.ts
            import {TestDirective} from '***'
            @NgModule({
                declarations:[TestDirective]
            })
    ②做爲標籤的屬性
        <h1 test></h1>

5.3 獲得調用指令的元素
    ①import {ElementRef} from '@angular/core'
    ②實例化
        constructor(private el:ElementRef){}
    ③讀取元素
        this.el.nativeElement

5.4 指令調用時傳參??
    ①<h1 test="123"></h1>
    ②在指令類的內部
        import {Input} from '@angular/core'

        @Input() test="";

        this.test

補充:使用生命週期的處理函數?
    ①引入
        import {OnDestroy} from '@angular/core'
    ②在定義類的時候 實現接口類
        export class Test implements OnDestroy{
            ngOnDestroy(){}
        }

6、組件之間通訊

Vue中組件通訊的方式?
    ①props down
        步驟1:發送
            <son myName="zhangsan"></son>
        步驟2:接收
            Vue.component('son',{
                props:['myName']
            })
    ②events up(子-》父)
        步驟1: 事件的綁定
            methods:{
                rcvMsg:function(msg){}
            }
            <son @customEvent="rcvMsg"></son>
        步驟2:事件的觸發(兒子)
            this.$emit('customEvent',123);
    ③$refs $parent
    ④bus
Angular中組件通訊?
    一、props down
        步驟1:發送
        <son uName="zhangsan"></son>
        步驟2:接收
            import {Input} from '@angular/core'
            @Input() uName="";
            this.uName
    二、events up
        步驟1:事件和處理函數的綁定
            定義一個方法
                rcvMsg(msg){}
            <son (toFatherEvent)="rcvMsg($event)">
            </son>
        步驟2:觸發事件
            子組件觸發
                import {Output,EventEmitter} from '@angular/core'

                @Output() toFatherEvent = new EventEmiiter();

                this.toFatherEvent.emit('123');

咱們是這樣寫 Angular 應用的:

用 Angular 擴展語法編寫 HTML 模板, 
用組件類管理這些模板,
用服務添加應用邏輯, 
用模塊打包發佈組件與服務。

7、管道(pipe)

管道是用來對數據進行篩選、過濾、格式化

Vue中過濾器:
    <any>{{expression | filter(1,2) | filter2 }}</any>

    Vue.filter('changeSex',function(arg,arg1,arg2){
        return 處理後的結果
    })

angular中管道:

過濾器的本質就是一個有參數有返回值的方法
    
    語法:
            <any>
            {{expression | pipe1:'12':34 | pipe2}}
            </any>
    
    一、內置管道
        
        常見內置管道:
            uppercase/lowercase/date/number/slice

    二、自定義管道
        建立一個自定義管道:
            import {Pipe,PipeTransform} from '@angular/core'

            @Pipe({
                name:'testNG'
            })

            export class TestPipe implements PipeTransform {
                    //value是豎槓前表達式執行的結果
                    //args經過調用管道時,冒號後邊跟的參數
                 transfrom(value:any,...args:[]):any{
                    return ‘處理後的結果’
                 }
            
            }
        
        調用:
            ①聲明
                到模塊中先引入再聲明
            ②調用
                和內置管道的用法是同樣的,一樣支持傳參、多重過濾

8、服務 (依賴注入)

服務 service:服務的本質是一個類,在服務類中封裝的是常常用到的數據和方法。

常見的服務:日誌類服務、心跳服務、網絡請求服務。。。

一、服務的建立和使用
    建立:
        import {Injectable} from '@angular/core'

        @Injectable()
        export class UserService {
            constructor(){}

            checkUserLogin(){return true}
        }

    使用:
        ①須要給服務指定provider
            在組件中或者模塊中指定providers:[UserService]
        ②調用
            import {UserService} from './***'

            constructor(private myService:UserService){}

            this.myService.checkUserLogin()



二、如何封裝一個網絡請求的服務

    ①建立服務的文件
    ②在服務中封裝一個方法
        sendRequest(myUrl:string){
            return  this.http.get(myUrl).map((response)=>
                response.json()
            )
        }
    ③調用以前 首先指定providers
    ④到組件中,先引入,再實例化,再調用
        this.myHS.sendRequest().subscribe((result)=>{
            //result就是服務器端返回的結果!
        })
    
    
    與服務器端通訊若是涉及的session,angular須要這麼處理:
        客戶端
            ①發起請求 withCredentials:true
                this.http.get(
        myUrl,
        {withCredentials:true}
        )
        服務器端:
            ①跨域header('Access-Control-Allow-Origin:http://localhost:3000');
            ②服務器容許接收憑證
            header('Access-Control-Allow-Credentials:true');


服務建立和使用:
    一、建立一個文件 test.service.ts
    二、在文件中編寫代碼,裝飾一個服務
        @Injectable()
        export class TestService{
            showAlert(msg){
                alert(msg);
            }
        }
    三、    給模塊或者組件,在providers屬性對應的數組中 [TestService]

    四、組件中要想使用服務中的方法
        import {TestService} from '***'

        constructor(private myService:TestService){}

        this.myService.showAlert()

Angular中開發模式:

咱們是這樣寫 Angular 應用的:
用 Angular 擴展語法編寫 HTML 模板, 
用組件類管理這些模板,
用服務添加應用邏輯, 
用模塊打包發佈組件與服務。

而後,咱們經過引導根模塊來啓動該應用。
Angular 在瀏覽器中接管、展示應用的內容,並根據咱們提供的操做指令響應用戶的交互。

在Angular開發時,八大組成部分:

一、模塊
二、組件
三、模板 自帶的html標籤+指令、綁定相關的ng的語法
四、元數據 告訴 Angular 如何處理一個類。
五、數據綁定
    {{}} () [] [(ngModel)]
六、指令 
        三大類:組件、結構型、屬性型
七、服務
    封裝一些數據和方法
八、依賴注入
    就是將依賴的服務、模塊注入到指定組件、模塊中取使用,提供了一種新的實例化的方式(解耦)

9、路由模塊

路由模塊:創建起url和頁面之間的映射關係
一、實現SPA的基本步驟

Vue:
實現一個SPA基本思路:
①指定一個容器
    <router-view></router-view>
②建立代碼片斷
    建立組件
    var Login = Vue.component('login-component',{
        template:`<h1>登陸頁面</h1>`
    })
③配置路由詞典
    new Vue({
        router:new VueRouter({
            routes:[
                {path:'/myLogin',component:Login}
            ]
        })
    })
④測試
    測試路由詞典中 路由地址可否按照需求 正確加載所須要用到的頁面

Angular:
①指定容器
    <router-outlet></router-outlet>
②建立組件 (聲明)
    @Component({}) export class **
③配置路由詞典
    //a-module-routing
    import {Routes,RouterModule} from '@angular/router'
    import {LoginComponent} from './demo15_spa/login.component'

    const routes:Routes = [
        {path:'',component:LoginComponent}
        .....
    ]

    @NgModule({
        import:[RouterModule.forRoot(routes)],
        exports:[RouterModule]
    })

    export class AppRoutingModule{}

    找到跟模塊:
        import {AppRoutingModule} from './app.router'

        @NgModule({
            imports:[AppRoutingModule]
        })
④測試

二、在Angular實現組件間的導航的方式

Vue寫法:
        ①能夠直接修改地址欄(內部測試)
        ②能夠經過js
         this.$router.push('目的地的路由地址')
        ③routerLink
         <router-link to="目的地的路由地址"></router-link>
Angular:
①直接修改地址欄
②js    
    import {Router} from '@angular/router'
    constructor(private myRouter:Router){}
    this.myRouter.navigateByUrl('url');
③ <a routerLink="地址"></a>



補充:實現前進和後退
    import {Location} from '@angular/common'

    constructor(private myLocation:Location){}

    this.myLocation.back();                this.myLocation.forward();

三、參數的傳遞

Angular:
    3.1 發送
        this.myRouter.navigateByUrl('myOC/123');

    3.2 接收
        ① 配置接收方的路由地址
            {path:'myOC'} ==> {path:'myOC/:price'}
        ② 接收參數
                import {ActivatedRoute} from '@angular/router'

                constructor(private myAR:ActivatedRoute){}

                this.myAR.params.subscribe((result)=>{
                    //result.price
                })
    
    在Angular中 實現數據傳輸的方式:
        ①組件間通訊
        ②跳轉時指定參數
        ③與遠程服務器端通訊

四、路由嵌套

能夠在SPA中某個組件中,根據url嵌套其它的組件
    Vue中實現方式:
        ①在準備嵌套其它組件的,指定一個容器 <router-view></router-view>
        ②配置路由詞典
            {
                path:'',
                component:MailComponent,
                children:[
                    {path:'inbox',component:***}
                ]
            }
    
    Angular中實現方式:
        ①指定容器
            router-outlet
        ②配置子路由
            {
                path:'mail',
                children:[
                    ...
                ]
            }

        總結:在Angular中實現一個支持路由嵌套的SPA,
        導航到對應的子路由對應的頁面時,必須在攜帶父組件的地址
            localhost:3000/mail/outbox
            localhost:3000/mail/inbox

        demo18_embed
            mylogin.component.ts  MyLoginComponent
            mail.component.ts MailComponent
            inbox.component.ts InboxComponent
            outbox.component.ts OutboxComponent
        ①完成組件的建立和聲明

        ②路由模塊

五、路由守衛

路由守衛 RouteGuard,控制是否可以訪問某一個url中所對應的組件!
    鑑權的組件
    用戶登陸的頁面
    。。。

如何使用路由守衛:
    ①建立一個服務
        import {Injecatable} from '@angular/core'
        import {CanActivate} from '@angular/router'

        @Injectable()
        export class MailGuard implments CanActivate{
        
            canActivate(){
                return true/false
            }
        }
    ②給服務指定提供商
         providers:[MailGuard]
    ③給路由詞典中想要保護的路由指定canActivate
            {
                path:'mail',
                canActivate:[MailGuard]
            }

    Vue中若是也想實現路由守衛:
        const router = new VueRouter({ ... })

        router.beforeEach((to, from, next) => {
            // ...
        })

        https://router.vuejs.org/zh-cn/advanced/navigation-guards.html
相關文章
相關標籤/搜索