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