- Angular介紹
- Angular安裝、創建項目、目錄結構、組件、服務
-
創建組件、綁定數據、綁定屬性、數據循環、條件判斷、事件、表單處理、雙向數據綁定
- 1. 創建組件
- 2. 綁定數據
- 3. 數據循環 *ngFor
- 4. 條件判斷
- 5. 執行事件
- 6. 綁定屬性
- 7. 表單處理
- 8. 雙向數據綁定 -
get post jsonp請求數據
- app.module.ts注冊HTPP JSONP服務 -
創建使用服務
- 創建服務
- app.moduel.ts引入服務
- 使用頁面引入、注冊服務
- 使用 - 父子組件傳值 @Input @Output @ViewChild
- 路由
Angular介紹
開源Web前端框架,被Google收購。
Angular 1.X 和 Angular 2.X 系列不一樣。同時維護 <br />
作用:<br />
APP和微信上的單頁面應用
借助Ionic、React Native開發跨平臺的原生APP
可以開發桌面應用,創建能在桌面環境下安裝的應用,橫跨Mac、Windows和Linu
x
<br />
特點:
組件化
模塊化
開發單頁面應用 <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, 微軟雅黑, "PingFang SC", Helvetica, Arial, "Hiragino Sans GB", "Microsoft YaHei", 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>
- 子組件引入 Input 模塊
import { Component, OnInit ,Input } from '@angular/core'; - 子組件中 @Input 接收父組件傳過來的數據export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
} - 子組件中使用父組件的數據
<h2>這是頭部組件--{{msg}}</h2>
2. 父組件傳值的方式讓子組件執行父組件方法
將方法名傳入,后執行。
- 父組件定義方法
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() { }
} - 子組件使用父組件的方法。
export class HeaderComponent implements OnInit {
@Input() msg:string;
@Input() run:any;
constructor() { }
ngOnInit() {
this.run(); /子組件調用父組件的 run 方法/
}
}
3. 子組件通過@Output執行父組件方法
EventEmitter:事件觸發器 emit:發出
- 子組件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
2.子組件中實例化 EventEmitter
@Output() private outer=new EventEmitter<string>();
/用 EventEmitter 和 output 裝飾器配合使用 <string>指定類型變量/
- 子組件通過 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. 父組件通過局部變量獲取子組件的引用,主動獲取子組件的數據和方法(一)
- 定義 footer 組件
export class FooterComponent implements OnInit {
public msg:string;
constructor() {
}
ngOnInit() {
}
footerRun(){
alert('這是 footer 子組件的 Run 方法');
}
} - 父組件調用子組件的時候給子組件起個名字
<app-footer #footer></app-footer>3. 直接獲取執行子組件的方法
<button (click)='footer.footerRun()'>獲取子組件的數據</button>
5. 父組件通過 ViewChild 主動獲取子組件的數據和方法
1.調用子組件給子組件定義一個名稱
<app-footer #footerChild></app-footer>
- 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core'; - ViewChild 和頁面引入的子組件關聯起來。別名一致
@ViewChild('footerChild') footer;
4.調用子組件
run(){
this.footer.footerRun();
}
## 路由
1. 創建一個配置好路由的項目
1.創建項目
ng new demo02 –-routing
- 創建需要的組件
ng g component home
ng g component news
ng g component newscontent - 找到 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'
}
]; - 找到 app.component.html 根組件模板,配置 router-outlet 顯示動態加載的路由
<h1>
<a routerLink="/home">首頁</a>
<a routerLink="/news">新聞</a>
</h1>
<router-outlet></router-outlet>
2. 給沒有路由的項目配置路由
新建組件
ng g component home
ng g component news
ng g component newscontent新建 app-routing.module.ts ,app-routing.module.ts 中引入模塊
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';app-routing.module.ts 中引入組件
import { HomeComponent } from './home/home.component';
import { NewsComponent } from './news/news.component';
import { NewscontentComponent } from './newscontent/newscontent.component';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'
}
];app-routing.module.ts 中配置模塊 暴露模塊
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }在 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 跳轉.
- 引入
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 傳值
- 引入 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';
- 配置路由
{
path: 'news',
component:NewsComponent,
children: [
{
path:'newslist',
component:NewslistComponent
},
{
path:'newsadd',
component:NewsaddComponent
}
]
} - 父組件中定義 router-outlet
<router-outlet></router-outlet>