Angular5学习笔记 - 创建服务(九)

一、创建服务

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

posted @ 2018-01-29 23:21  昨日微风  阅读(415)  评论(0编辑  收藏  举报