angular6 服务获取数据 组件在引入服务 展示在视图上


 

环境

前端:angular6

后端:thinkphp5

 

使用场景

1.服务service 获取后端接口数据

2.组件componment 引用服务处理,并展示数据到前台

3.前台*ngFor 遍历出数据

 

实例:

一、nav.service.ts 菜单数据从接口获取

①import HttpClient 、Observable、Injectable、OnInit、Nav(定义数组格式)

②Injectable注入 使用cli命令 ng g service 服务名 创建自动搞定

③HttpClient 初始化 

constructor(private http: HttpClient ) { }

④定义函数接收数据 ,使用Observable

1)首先定义一个API接口地址

private _navApiUrl = 'apidata/api/Nav/index'; 这里 /apidata  进行了URL重写

2)然后定义一个接收后端数据的函数 getnavdata() 使用http.get返回的是Obervable对象

使用Observable<Nav[]> 在组件里获得结果就要使用subscribe解析出来

getnavdata(): Observable<Nav[]> {

return this.http.get<Nav[]>(this._navApiUrl);

}

这里就三点注意

1.函数后面冒号(:)紧跟Obsevable<xxx> 同样的http.get<xxx>也要使用

2.结束使用return返回数据 此时返回的是Observable对象的数据

3.注意使用空格 容易造成格式错误比如:冒号后空格 ,还有大括号前空格

这里的Nav[] 就是单独定义的数组结构

nav.ts

export class Nav {
id: number;
name: string;
}

 

3)

 

 

 实例nav.service.ts

 

import {Injectable, OnInit} from '@angular/core';
import { HttpClient} from '@angular/common/http';

import { Observable } from 'rxjs/index';

import { Nav } from './nav';

@Injectable({
  providedIn: 'root'
})
export class NavService implements OnInit {

  constructor(private http: HttpClient ) { }

    private _navApiUrl = 'apidata/api/Nav/index';

   getnavdata(): Observable<Nav[]> {

       return this.http.get<Nav[]>(this._navApiUrl);


  }

  ngOnInit() {


  }

}

 

参考服务建立命令

D:\cmf\angular6\project1>ng g s service\formadd

 

  

 

二、组件

1.导入服务nav.service

2.注入服务 constructor(public navservice: NavService) { }

 

 

import { Component, OnInit } from '@angular/core';

import { NavService } from '../nav.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css'],
})

export class NavComponent implements OnInit {


  public nav: any;

  constructor(public navservice: NavService) { }

  getnavdata(): void {
   this.navservice.getnavdata().subscribe(
         data => {
             this.nav = data;
             console.log(data);
         }
     );
     console.log('component:');
     console.log(this.navservice.getnavdata());
     return this.nav;
  }


  ngOnInit() {
     this.getnavdata();
  }
 

 

 

3.视图跟新

nav.component.html

 

    <ul class="row">
        <li ngbDropdown *ngFor="let navs of  nav" class="col-lg-2">

          <a href="{{ navs.href}}}" id="dropdownBasic2" ngbDropdownToggle>{{ navs.name }}</a>
          <div ngbDropdownMenu aria-labelledby="dropdownBasic2">
            <button class="dropdown-item">Action - 1</button>
            <button class="dropdown-item">Another Action</button>
            <button class="dropdown-item">Something else is here</button>
          </div>


        </li>
      </ul>

  

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM