以角度2从ReST Micro服务获取数据

时间:2017-11-15 10:35:33

标签: angular spring-boot

我正在尝试从ReST Micro服务获取数据,该服务以JSON格式提供数据(用户名和密码)([{"用户名":" Mark",&#34 ;密码":" mark123"}])通过其端点 " http://localhost:8080/checkUsers"

我使用userdetail.component.ts文件和user.service.ts在angular 2中创建了一个简单的应用程序,该文件从位于我的应用程序的assets文件夹中的apidata文件夹中的userdata.json文件中提取数据

下面显示的是我的代码

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Http, Response} from '@angular/http';

import { AppComponent } from './app.component';
import { UserListComponent } from './user-list.component';
import {  UserDetailComponent } from './user-detail.component';
import { UserService } from './user.service';

@NgModule({
  declarations: [
    AppComponent,
    UserListComponent,
    UserDetailComponent
  ],

  imports: [ BrowserModule, HttpModule ],

  providers: [UserService],

  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',

  providers: [UserService]


})
export class AppComponent {
  title = '';
}

app.component.html

 <user-detail></user-detail>

用户detail.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';

@Component({
    selector: 'user-detail',
    template: `<h4>User Details</h4>'
                <ul *ngFor=" let user of users ">
                <li>username={{user.username}}-------password={{user.password}}</li>
                </ul>`
})

export class UserDetailComponent implements OnInit{
users = [];

constructor(private _userService:UserService){}
ngOnInit(){
this._userService.getUsers()
.subscribe(resUserData => this.users = resUserData);
}
}

user.service.ts

import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {
private _url: string = "http://localhost:4200/assets/apidata/userdata.json"
constructor(private _http: Http){}
    getUsers(){
    return this._http.get(this._url)
    .map((response:Response) => response.json() );
}}

任何人都可以请指导我在角度2应用程序中从ReST微服务获取数据的过程。

1 个答案:

答案 0 :(得分:0)

在使用REST时,我们需要在加载(初始化)组件之前预先获取基本数据。要实现此目的,请实施解析程序并在实施时使用该服务。

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { UserService } from './user.service';


@Injectable()
export class UserDataResolver implements Resolve<any> {

    constructor(private userService: UserService,
                private router: Router) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return this.userService.getUsers()
            .map(response => {
                let users = response['users'];
                if (users) {
                    return users;
                }
                console.log(`NO users`);
                //navigate if you want to....
                this.router.navigate(['']);
                return null;
            })
            .catch(error => {
                console.log(`Retrieval error: ${error}`);
                this.router.navigate(['']);
                return Observable.of(null);
            });
    }
}

现在将此解析器与路径一起使用以通过REST加载数据

const appRoutes: Routes = [
    {
     path: '',
     component: AppComponent,
     children: [
      { path: 'user', component: UserComponent, resolve: { users: UserDataResolver } }
     ]
    },
    { path: '**', component: PageNotFoundComponent }

];

在组件中访问此数据:

@Component({
  selector: 'user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.css']
})
export class UserDetailComponent implements OnInit {

  usersList:any;
  constructor(private route: ActivatedRoute) {
   }

  ngOnInit() {
    this.usersList = this.route.snapshot.data['users'];
  }

}

如果您想在使用组件时获取其他一些数据,请通过直接注入组件的服务获取它。