import { Links } from './links';
export class User {
constructor (
public username: string = null,
public password: string = null,
public _links: Links = null,
) { }
}
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Response } from '@angular/http';
import { User } from './user';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class UserService {
constructor (
private http: Http
) { }
private url = 'http://localhost:8080/user'
getAllUsers(): Promise {
return this.http.get(this.url)
.toPromise()
.then(this.extraData)
.catch(this.handleError);
}
private extraData(response: Response) {
return response.json()._embedded['user'];
}
private handleError (error: any) {
let msg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'unknown error';
console.error(msg); // log to console instead
return Promise.reject(msg);
}
}
Angular同样使用了MVC设计模式。所以我们在文件命名中,可以看到.module.ts,.component.ts,.component.html,.service.ts。按照AngularJS的命名习惯,调用后台RESTful API的代码应该放在service里面,并且在需要用到该service的module里面,用@NgModule注释的providers注入。这样该module对应的Component就可以使用了。请参考下面的home.module.ts,home.component.ts,注意UserService类并没有被显式的实例化,而只是在home.module.ts用@NgModule注释进行了依赖注入,然后在HomeModule的构造里面声明了一个private的UserService的成员。另外可以依赖注入的组件,需要用@Injectable注释声明,就像UserService类那样。依赖注入的管理是AngularJS2的一个重要功能。
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UserService } from '../shared/user.service';
import { HomeComponent } from './home.component';
@NgModule({
imports: [
CommonModule,
],
declarations: [
HomeComponent,
],
providers: [
UserService
]
})
export class HomeModule { }
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { User } from '../shared/user';
import { UserService } from '../shared/user.service';
import { Subscription } from 'rxjs/Subscription' ;
@Component({
templateUrl: '/app/home/home.component.html'
})
export class HomeComponent implements OnInit, OnDestroy {
subscription: Subscription;
users: User[];
constructor(
private router: Router,
private route: ActivatedRoute,
private userService: UserService,
) { }
ngOnInit() {
this.userService.getAllUsers().then(
users => {
console.log(users);
this.users = users;
},
error => console.error(error)
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
templateURL指明了对应的视图。HomeComponent调用UserService的getAllUsers取得全部user,然后通过视图表现出来。视图大部分的代码跟标准HTML没有区别。AngularJS2最重要的特性之一就是支持双向绑定。目前home.component.html的代码使用的{{ }}只是单向绑定,即从模型到视图。双向绑定的列子我们放到后面。{{ }}相当于ngModel指令。ngFor指令实现了for循环。注意前面的*不能省略。
Welcome to Healtrav
All users
-
username: {{ user.username }}
password: {{ user.password }}
_links.self.href: {{ user._links.self.href }}
No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是因为Spring默认的HTTP Response,不会添加Access-Control-Allow-Origin这个HTTP头。其中一个解决方案是配置Spring,添加这个头,请参考Spring的官方文档:https://spring.io/guides/gs/rest-service-cors/。另外一个解决方案将在下一章讲。
npm install -g angular-cli
ng new PROJECT_NAME
cd PROJECT_NAME
ng serve
打开网页http://localhost:4200/即可以访问。
ng g component my-new-component
其它的service,module,等等,都可以用类似的命令产生。
ng build
之后在dist目录下面产生打包文件。
ng build --prod --aot
ng build --bh /myUrl/
ng test