angular使用service应用分层
step0:创建一个新项目
step1: 创建服务user和组件user
ng generate service user
ng generate component user
step2: 创建bean类 D:\vue\untitled2899\src\app\user.ts
export class User {
id: number;
name: string;
address: string;
constructor(id: number, name: string, address: string) {
this.id = id;
this.name = name;
this.address = address;
}
}
step3: 创建本地资源库 D:\vue\untitled2899\src\app\mock-users.ts
import {User} from "./user";
export const USERS : User[] = [
{id:11,name:'李明',address:'北京'},
{id:12,name:'刘洪',address:'上海'},
{id:13,name:'赵雄',address:'深圳'},
{id:14,name:'楚飞',address:'郑州'},
{id:15,name:'宋苗',address:'贵阳'},
{id:16,name:'林峰',address:'周口'},
{id:17,name:'周海',address:'洛阳'},
{id:18,name:'洪涛',address:'楚雄'},
{id:19,name:'毕畅',address:'荆州'},
{id:20,name:'黄平',address:'怀化'},
];
step4: 自动添加组件 D:\vue\untitled2899\src\app\app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
@NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
step6: 将user组件集成到主界面 D:\vue\untitled2899\src\app\app.component.html
{{title}}
<app-user></app-user>
step7: 服务类user D:\vue\untitled2899\src\app\user.service.ts
import {Injectable} from '@angular/core';
import {Observable, of} from "rxjs";
import {User} from "./user";
import {USERS} from "./mock-users";
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor() {
}
getUsers(): Observable<User[]> {
return of(USERS);
}
}
step8: user组件类 D:\vue\untitled2899\src\app\user\user.component.ts
import { Component, OnInit } from '@angular/core';
import {User} from "../user";
import {UserService} from "../user.service";
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
users:User[] | undefined;
constructor(private userService:UserService) { }
ngOnInit(): void {
this.getUsers();
}
getUsers():void{
this.userService.getUsers().subscribe(users => this.users = users);
}
}
step9: user组件布局 D:\vue\untitled2899\src\app\user\user.component.html
<h2>我的用户</h2>
<ul class="users">
<li *ngFor="let user of users">
<span class="badge">{{user.id}}</span> {{user.name}}
</li>
</ul>
run,发现可以展示一个列表数据
end