1. 程式人生 > >Angular5學習筆記 - 創建服務(九)

Angular5學習筆記 - 創建服務(九)

sym oca cal gen temp 創建服務 .get ide use

一、創建服務

ng generate service service-name #簡寫 ng g s component-name
ng g s services/userService

二、效果

技術分享圖片

三、開發服務

修改\src\app\services\user-service.service.ts文件

import { Injectable } from ‘@angular/core‘;
import { Http } from ‘@angular/http‘;
import ‘rxjs/add/operator/toPromise‘;

@Injectable()
export class UserServiceService {
  
private api = ‘http://localhost:3003‘; // 服務器地址 private gundamList = ‘/news‘; // 獲取全部 private getGundam = ‘/detail‘; // 獲取明細 constructor(private http: Http) { } // 獲得全部數據 getGundams(): Promise<any[]> { return this.http.get(this.api + this.gundamList) .toPromise() .then(response
=> response.json()) .catch(this.handleError); } // 根據Id查詢高達 getGundamById(id: number): Promise<object> { console.log(this.api + this.getGundam + ‘?id=‘ + id); return this.http.get(this.api + this.getGundam + ‘?id=‘ + id) .toPromise() .then( response
=> response.json()) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error(‘An error occurred‘, error); // for demo purposes only return Promise.reject(error.message || error); } }

四、全局註冊服務

修改\src\app\app.module.ts文件

import {UserServiceService} from ‘./services/user-service.service‘;


  /* 註冊服務 */
  providers: [UserServiceService],

五、使用服務

修改\src\app\components\users\list\list.component.ts文件

import {Component, OnInit} from ‘@angular/core‘;
/*import { Http } from ‘@angular/http‘; 添加Http請求模塊 */
import {UserServiceService} from ‘../../../services/user-service.service‘;
import {
  ActivatedRoute,
  Params
} from ‘@angular/router‘;

@Component({
  selector: ‘app-list‘,
  templateUrl: ‘./list.component.html‘,
  styleUrls: [‘./list.component.css‘]
})
export class ListComponent implements OnInit {
  /* 變量定義 */
  data:object[] = [];/* 定義列表數據變量 */
  
  /* 構造方法,做依賴註入 */
  constructor(
    // private _httpService: Http,
    private route: ActivatedRoute,
    private _userServiceService: UserServiceService
  ) {

  }

  /* 加載完事件,做初始化 */
  ngOnInit() {
    // this._httpService.get(‘http://localhost:3003/news‘).subscribe(values => {
    //   console.log(values);
    //   this.data = values.json();
    // });
    this._userServiceService.getGundams().then(gundams => this.data = gundams.slice(0, 3)); // 讓主頁只顯示3個
  }

}

備註:

Error: ELOOP: too many symbolic links encountered……
ELOOP: too many symbolic links encountered, stat ……

六、運行效果,可正常請求到數據。

技術分享圖片

解決方案

刪除node_modules文件夾, 重新npm install,不能用cnpm

Angular5學習筆記 - 創建服務(九)