定义服务service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import {Injectable} from "@angular/core"; import {Nav} from "./navs"; import {Http} from "@angular/http"; import {Observable} from "rxjs/Rx"; @Injectable() export class NavServiceService { constructor(private http:Http) { } getNavs():Observable<Nav[]> { return this.http.get("http://localhost:9999/api/greeting") .map(res => res.json()); } } |
调用服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import {Component, OnInit} from "@angular/core"; import {Nav} from "./navs"; import {NavServiceService} from "./nav-service.service" @Component({ selector: 'app-nav', templateUrl: './nav.component.html', styleUrls: ['./nav.component.css'], providers: [NavServiceService] }) export class NavComponent implements OnInit { navs:Nav[]; constructor(private navService:NavServiceService){} getNavs():void { this.navService.getNavs().subscribe(res =>{this.navs = res}); } ngOnInit() { this.getNavs(); } } |
springboot接口实现
greetController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@RestController @CrossOrigin @RequestMapping("/api") public class GreetingController { private final AtomicLong counter = new AtomicLong(); Greeting[] gr = new Greeting[3]; @RequestMapping("/greeting") //这里应调用数据库循环赋值 public Greeting[] greeting() { for(int i = 0;i< gr.length; i++){ gr[i] = new Greeting("formControls", "none", "/form"); } return gr; } } |
Greeting
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Greeting { private final String barName; private final String barClass; private final String link; public Greeting(String barName, String barClass, String link) { this.barName = barName; this.barClass = barClass; this.link = link; } public String getBarName() { return barName; } public String getBarClass() { return barClass; } public String getLink() { return link; } } |