如何在角度编辑操作?

时间:2018-10-01 11:13:07

标签: angular angular6 crud

我正在尝试进行粗鲁的操作。我能够执行创建和删除操作。我希望在单击编辑功能然后可以更改它们时将现有数据显示在输入表单中。有人可以帮我进行编辑操作吗?

这是我的代码

service.ts

import { Injectable} from '@angular/core';
import{UserCreation} from '../../models/user-creation.model';
import{Observable} from 'rxjs/Observable';
import{of} from 'rxjs/observable/of';
import{catchError,map,tap} from 'rxjs/operators';
import{HttpClient,HttpHeaders} from '@angular/common/http';

const httpOptions={
headers:new HttpHeaders({'Content-Type':'application/json'})
};

@Injectable({
providedIn: 'root'
})

export class UserCreationService{

constructor(private http:HttpClient) { }

private usersUrl='https://jsonplaceholder.typicode.com/posts';

getUsers():Observable<UserCreation[]>{
return this.http.get<UserCreation[]>(this.usersUrl).pipe(
tap(receivedUsers 
=>console.log(`receivedUsers=${JSON.stringify(receivedUsers)}`)),
  catchError(error=>of([]))
);
}

getUserFromId(id:number):Observable<UserCreation>{

const url=`${this.usersUrl}/${id}`;
return this.http.get<UserCreation>(url).pipe(
  tap(selectedMovie=>console.log(`selected movie 
 =${JSON.stringify(selectedMovie)}`)),
  catchError(error=>of(new UserCreation()))
)
}

updatedUser(user:UserCreation):Observable<any>{

return 
this.http.put(`${this.usersUrl}/${user.id}`,user,httpOptions).pipe(
  tap(updatedUser=>console.log(`updated user 
=${JSON.stringify(updatedUser)}`)),
  catchError(error=>of(new UserCreation()))
)
}

addUser(newUser:UserCreation):Observable<UserCreation>{
return this.http.post<UserCreation> 
(this.usersUrl,newUser,httpOptions).pipe(
  tap((user:UserCreation)=>console.log(`inserted 
movie=${JSON.stringify(user)}`)),
  catchError(error=>of(new UserCreation()))
)
}

deleteUser(userId:number):Observable<UserCreation>{
const url=`${this.usersUrl}/${userId}`;
return this.http.delete<UserCreation>(url,httpOptions).pipe(
  tap(_=>console.log(`Deleted movie with id = ${userId}`)),
  catchError(error=>of(null))
)
}


}

component.ts

我这里需要编辑功能

import { Component, OnInit } from '@angular/core';
import { UserCreation} from '../../models/user-creation.model';
import { UserCreationService } from '../../common/services/user- 
creation.service';

@Component({
selector: 'app-user-management',
templateUrl: './user-management.component.html',
styleUrls: ['./user-management.component.css']
})

export class UserManagementComponent implements OnInit {

allUsers: UserCreation[];

constructor(private userService: UserCreationService) { }


getUsersFromServices():void{
this.userService.getUsers().subscribe(
  (Users)=>{
    this.allUsers=Users;
    console.log(Users);

  }
 )
}

ngOnInit(): void {
this.getUsersFromServices();
}


add(title:string,body:string):void{
const newUser:UserCreation=new UserCreation();
newUser.title=title;
newUser.body=body;
this.userService.addUser(newUser)
.subscribe(insertedUser=>{
  this.allUsers.push(insertedUser);
});
}


delete(userId:number):void{
this.userService.deleteUser(userId).subscribe(_=>{
  this.allUsers=this.allUsers.filter(eachUser=>eachUser.id!==userId);
})
}

component.html

我想知道编辑按钮会出现什么

<table class="row-border hover">
 <tr *ngFor="let user of allUsers " >
   <td>{{user.title}}</td> <td>{{user.body}}</td>

   <td><button type="button" 
   (click)="Edit()">Edit</button> </td> 

  <td><button type="button" (click)="delete(user.id)">Delete</button> 
  </td>
 </tr>
</table>

<form>
<div class="form-group">
  <label for="text">Title:</label>
  <input type="text" class="form-control" id="text" name="title" 
  #title>
</div>

<div class="form-group">
  <label for="text">Body:</label>
  <input type="text" class="form-control" id="text" name="body" #body                 
</div>

<button type="submit" class="btn btn-primary" 
(click)="add(title.value,body.value); title.value=''; 
body.value=''">Submit</button>
</form>

model.ts

export class UserCreation{
id:number;
title:string;
body:string;
}

1 个答案:

答案 0 :(得分:0)

在component.html中,您需要在编辑单击中添加ID,以查找需要编辑的用户详细信息,并使“标题”和“正文”成为双向数据绑定模型,以查看编辑时的用户详细信息。

<input type="text" class="form-control"  [(ngModel)]="title" id="text" name="title" #title>
<input type="text" class="form-control"  [(ngModel)]="body" id="text" name="body" #body  >

 <button type="button" (click)="Edit(user.id)">Edit</button> 

在component.ts中添加方法Edit(id)以从用户列表中获取用户的详细信息:

Edit(editUserID){
var user = this.allUsers.find(user=>user.id == editUserID);
this.title=user.title;
this.body=user.body;
}

在“保存”按钮中单击,您可以使用ID更新用户列表。