Angular7建立專案、元件、服務以及服務的使用
三大前端專案就剩angular沒學了,在網上找了幾個教程,這裡總結一下,方便以後用到時查閱
建立專案
首先安裝cli工具
npm install -g @angular/cli
建立一個空專案, 有兩處要選擇的,一個是路由,我這裡是要路由的,還有一個開發css的語言,我這裡選擇scss,就不截圖了,選完後會自動通過yarn安裝依賴,稍等一會就好了
ng new pybbs-front-angular
建立好了,執行 npm run start
或者 ng serve
啟動服務,然後就可以在瀏覽器裡開啟 http://localhost:4200/
地址檢視啟動後的首頁了
建立元件
命令 ng g component user
執行完後,會在 src/app
目錄下生成一個user的資料夾,裡面有四個檔案
如果想把元件都放在一個資料夾裡管理,也可以在建立的時候加上一個資料夾名字,比如把所有的元件都放在 components
資料夾裡,命令就是這樣的 ng g component components/user
頁面名 | 說明 |
---|---|
user.component.html | 元件模板檔案 |
user.component.scss | 元件的樣式檔案 |
user.component.spec.ts | 元件測試檔案 |
user.component.ts | 元件檔案 |
使用命令建立元件有個好處就是cli會自動把這個元件引入到 src/app/app.module.ts
檔案裡,這樣直接在其它檔案裡使用 src/app/user/user.component.ts
裡定義的 selector
,一般這個名字都是 app-xxx
後面xxx就是這個模組的名字,比如這裡的user模組,就是 app-user
生命週期
angular的生命週期有很多,看下下圖
這裡只介紹二個
方法 | 說明 |
---|---|
ngOnInit | 元件載入時初始化變數或者網路請求時程式碼寫在這裡面 |
ngAfterViewInit | 如果想對頁面進行dom操作,最好在這個方法裡操作,這個方法是在頁面dom元素都載入完成後才呼叫的 |
建立服務
命令 ng g service user
執行完後,cli會自動建立兩個檔案在 src/app/user
資料夾裡
如果想把服務也都放在一個資料夾裡管理,可以在命令上加上一個服務的資料夾名字,如 ng g service services/user
服務檔名 | 說明 |
---|---|
user.service.ts | 元件提供服務的主檔案 |
user.service.spec.ts | 元件提供服務檔案的測試檔案,寫對服務測試的程式碼都放在這裡面 |
服務建立好了之後,沒有建立元件那麼方便了,還需要自己配置一下,開啟 src/app/app.component.ts
檔案
在檔案內引入,然後將服務注入到 providers 裡
import { UserService } from './user/user.service'; @NgModule({ providers: [ UserService ] })
首先新增一個服務 user.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class TopicService { constructor(private http: HttpClient) { } fetchGithubApi() { return new Observable((observe) => { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; this.http.get('https://api.github.com', httpOptions) .subscribe((data: any) => { observe.next(data.detail); // 如果有錯誤,通過 error() 方法將錯誤返回 // observe.error(data.description); }); }); } }
開啟 user.component.ts
檔案,使用這個服務裡定義的方法,程式碼如下
引入服務檔案,然後初始化,這裡初始化有兩種方式,一種 private userService: UserService = new UserService()
,另一種是通過構造方法注入
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { UserService } from './user.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class UserComponent implements OnInit { constructor( private userService: UserService ) { } ngOnInit() { this.userService.fetchGithubApi() .subscribe(data => console.log(data), error => console.log(error)); } }
說明:上面例子中請求介面用的是 angular 內建好的 rxjs 模組,你也可以換成流行的 axios 或者其它的框架
原文連結: