AngularJS PWA 製作

ng new pwademo
cd pwademo
ng add @angular/material

設定HttpClient

  • import HttpClientModule 模組至src/app/app.module.ts
/*...*/
import { HttpClientModule } from  '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
/*...*/
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export  class  AppModule { }

建立Service

ng g service api  // 此指令會在 src/app/api.service.ts 建立ApiService
  • api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
import { Observable } from  'rxjs';

export  interface  Item {
   name:  string;
   description:  string;
   url:  string;
   html:  string;
   markdown:  string;
}

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private  dataURL:  string  =  "https://www.techiediaries.com/api/data.json";

  constructor(private  httpClient:  HttpClient) {}

  fetch():  Observable<Item[]> {
   return <Observable<Item[]>> this.httpClient.get(this.dataURL);
  }

}

使用Service

  • 開啟 src/app/app.component.ts
import { Component } from '@angular/core';
import { ApiService } from  './api.service';
import { Item } from  './api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
   title = 'pwademo';   
   items:  Array<Item>;

   constructor(private  apiService:  ApiService) {

   }

   ngOnInit() {
      this.fetchData();
   }

   fetchData(){
      this.apiService.fetch().subscribe((data:  Array<Item>)=>{
         console.log(data);
         this.items  =  data;
      }, (err)=>{
         console.log(err);
      });
   }

}

增加UI畫面

  • 編輯 src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';

import { MatToolbarModule } from  '@angular/material/toolbar';
import { MatCardModule } from  '@angular/material/card';
import { MatButtonModule } from  '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    MatCardModule,
    MatButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  • 開啟 src/app/app.component.html

執行

ng build --prod
npm i -g http-server

參考資料