我正在创建一个Angular6 crud应用程序,我的数据库中有一个用户列表。当我调用getAllUsers时,我能够检索我的列表,但它不会显示在UI中。我在表中看到一行显示的唯一一次是当我手动输入新用户但它没有显示我输入之前的数据。我究竟做错了什么?
import { Component, OnInit } from '@angular/core';
import { UserDataService } from './user-data.service';
import { User } from './user';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserDataService]
})
export class AppComponent implements OnInit{
users: User[]=[];
constructor(private userDataService: UserDataService) {}
public ngOnInit() {
debugger
this.userDataService
.getAllUsers()
.subscribe(
(users) => {
this.users = users;
}
);
}
onAddUser(user) {
this.userDataService
.addUser(user)
.subscribe(
(newUser) => {
this.users = this.users.concat(newUser);
}
)
}
onRemoveUser(user){
this.userDataService
.deleteUserById(user.id)
.subscribe(
(_) => {
this.users = this.users.filter((u) => u.id !== user.id);
}
);
}
getUser() {
return this.userDataService.getAllUsers();
}
}
APP COMPONENT HTML
<app-user-list-header (add)="onAddUser($event)"></app-user-list-header>
<table>
<th>ID</th>
<th>NAME</th>
<tr *ngFor = "let user of users">
<td>{{user.id}}</td>
<td>{{user.userName}}</td>
</tr>
</table>
用户数据服务
import { Injectable } from '@angular/core';
import { User } from './user';
import { ApiService } from './api.service';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserDataService {
constructor(private api: ApiService) { }
addUser(user: User): Observable<User> {
return this.api.createUser(user);
}
getAllUsers(): Observable<User[]> {
return this.api.getAllUsers();
}
updateUser(user: User): Observable<User> {
return this.api.updateUser(user);
}
getUserById(userId: number): Observable<User> {
return this.api.getUserById(userId);
}
deleteUserById(userId: number): Observable<User> {
return this.api.deleteUserById(userId);
}
}
用户列表标题
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { User } from '../user';
@Component({
selector: 'app-user-list-header',
templateUrl: './user-list-header.component.html',
styleUrls: ['./user-list-header.component.css']
})
export class UserListHeaderComponent implements OnInit {
newUser: User = new User();
@Output()
add: EventEmitter<User> = new EventEmitter();
constructor() { }
ngOnInit() {
}
addUser() {
this.add.emit(this.newUser);
this.newUser = new User();
}
}
用户列表标题HTML
<header class="userHeader">
<h1>Users</h1>
<input class="new-user" placeholder="Enter User" autofocus="" [(ngModel)]="newUser.userName" (keyup.enter)="addUser()">
</header>
API服务
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { User } from './user';
import { Http } from '@angular/http';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from "rxjs/operators";
const API_URL = environment.apiUrl;
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {
}
public createUser(user: User): Observable<User> {
const headers = {headers: new HttpHeaders({
'Content-Type': 'application/json'
})};
return this.http
.post(API_URL + '/users', user).pipe(
map(response => {
return new User(response);
}), catchError(this.handleError)
)
}
public getAllUsers(): Observable<User[]> {
return this.http
.get(API_URL + '/users').pipe(
map(response => {
var users = [response];
return users.map((user)=> new User(user));
}), catchError(this.handleError))
}
答案 0 :(得分:1)
问题是,在您之前完成之后,您不需要再次在AppComponent中将新用户订阅到observable:
.subscribe(
(newUser) => {
this.users = this.users.concat(newUser);
}
)
因为它已经通过以下方式添加到用户数组:this.userDataService.addUser(user)
,表示您向观察者插入了两次相同的值。
所以你需要做的是,在userdata服务中,将观察者插入到其余api中,该api定期将数据提取到适配器getAllUsers
,如下所示:
getAllUsers(): Observable<user[]> {
// some intermediate post call happens here
this.api.getAllUsers().subscribe((users) => users.map((user)=>this.users.push(user)));
return of(this.users);
}
每当新值添加到用户群或通过其他呼叫进行管道传输时,这将更新用户的状态,因此您永远不必从同一观察者多次订阅相同的值,这将导致数据重复。
我找不到允许发布电话的在线API,所以你可以使用自己的工具找到我上面说的那么容易,但对于同域GET api服务,我在这个术语中做了一个例子可见在这里你的眼睛:
https://stackblitz.com/edit/angular-rndqsd。 为了词汇津贴而将国家作为用户。