これは、テーブルをクリックすると私のUsersListコンポーネントです。新しいページは、ユーザーの値を変更し、それを保存する際
を開かれ、保存された値は、初めてのグリッドには反映されません。しかし、私は再び同じ操作を行うと、それが反映されています。
以下は私の保存・ユーザ・コードである私は理解していなかった何
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { UserService } from './../../shared/services/user.service';
import {User} from './../../shared/models/user';
@Component({
selector: 'app-user-add-edit',
templateUrl: './user-add-edit.component.html',
styleUrls: ['./user-add-edit.component.css']
})
export class UserAddEditComponent implements OnInit {
private user: User;
private id:Number;
constructor(private userService: UserService, private route: ActivatedRoute,private router: Router) { }
ngOnInit() {
this.id = Number(this.route.snapshot.params['id']);
if (this.id) {
this.userService.read(this.id).subscribe(
users => this.user = users,
err => {
console.log(err);
}
);
}
}
saveUser(){
this.userService.update(this.user.client,this.user.firstName,this.user.lastName,this.user.id,this.user.key).subscribe(
users => this.user = users,
err => {
console.log(err);
}
);
this.router.navigateByUrl("users");
}
}
たにもかかわらずthis.router.navigateByUrl(「ユーザー」); は、saveがobservableからの応答を受け取った後に呼び出されます。なぜ初めてテーブルで更新されないのですか?
ユーザーの編集コンポーネント
<div class="container">
<h1 class='text-info' >Edit Users</h1>
<div class="form-container">
<form (ngSubmit)="saveUser()">
<div class="form-group">
<hr>
<label for="name" class='text-info'><b> Client</b></label>
<input type="text" name="client" [(ngModel)]="user.client" class="form-control" required />
</div>
<div class="form-group">
<label for="name" class='text-info'><b>FirstName</b></label>
<input type="text" name="firstName" [(ngModel)]="user.firstName" class="form-control" required />
</div>
<div class="form-group">
<label for="name" class='text-info'><b>LastName</b></label>
<input type="text" name="lastName" [(ngModel)]="user.lastName" class="form-control" required />
</div>
<div class="form-group">
<a class="btn btn-default" routerLink="/users">Cancel</a>
<button class="btn btn-primary">Save</button>
<button class="btn xs btn-danger" (click)="deleteUser(user.id)">Delete</button>
</div>
</form>
</div>
</div>
ユーザーサービス
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
import { Component, OnInit, Injectable } from '@angular/core';
import { Http, Request, RequestMethod, RequestOptions, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {User} from './../../shared/models/user';
@Injectable()
export class UserService implements OnInit {
private appContent = 'application/json';
private _router: Router;
private baseUrl = 'http://localhost:5000/api/v1/';
//Constructor to initialize authService to authenticate user, http to send the CRUD request and Router for the resource
constructor(private authService: AuthService, private http: Http,private router: Router) {
}
ngOnInit() {
}
//For creating a user Client,Key,Firstname and lastName has to be passed
create(client: string, key: string, firstName: string, lastName: string) :Observable<boolean> {
//createAuthenticatedRequest is called before sending the Http request
let request = this.createAuthenticatedRequest(JSON.stringify({client: client, key: key, firstName: firstName, lastName: lastName}),RequestMethod.Post);
return this.http.request(request).map(r=>{
r.ok;
}).catch((error: any) =>{
return Observable.throw(error);
});
}
update(client: string, firstName: string, lastName: string,id: number, key: string) :Observable<any> {
var request = this.createAuthenticatedRequest(JSON.stringify({client: client, key: key, firstName: firstName,
lastName: lastName, id:id}),RequestMethod.Put, id.toString());
return this.http.request(request).map(r=>{
r.json;
console.log(r);
}).catch((error: any) =>{
console.log(error);
return Observable.throw(error);
});
}
delete(client: string, key: string, firstName: string, lastName: string,id: number):Observable<boolean> {
var request = this.createAuthenticatedRequest(JSON.stringify({client: client, key: key, firstname: firstName, lastName: lastName}),RequestMethod.Delete, id.toString());
return this.http.request(request).map(r=>{
r.ok;
}).catch((error: any) =>{
return Observable.throw(error);
});
}
//Read method takes an optional input id, If id is not passed to read it will get the entire list , else it will get the record with specified id
read(id?: Number):Observable<any> {
id = (id == undefined) ? 0 : id ;
if (id >0)
// Get single resouce from Collection
var request = this.createAuthenticatedRequest(null,RequestMethod.Get, id.toString());
else
// Get the entire collection
request = this.createAuthenticatedRequest(null,RequestMethod.Get, id.toString());
return this.http.request(request).map(r=>{
console.log(r.text());
return JSON.parse("[" + r.text() + "]")[0];
}).catch((error: any) =>{
return Observable.throw(error);
});
}
//This method accepts json of the attribtes client,key,firstname and lastName and request method(Post/Get/Put/delete) and
//an optional parameter id , This method's return type is Request
createAuthenticatedRequest(json : string, reqMethod: RequestMethod, optionalparam?: string) : Request{
//checks if the user is authenticated user with authentication service method isAuthenticated
if (this.authService.isAuthenticated()) {
console.log('authenticated');
optionalparam =(optionalparam==undefined || optionalparam =='0') ? "" : optionalparam;
const request = new Request({
method: reqMethod,
url: this.baseUrl + 'creds/' + optionalparam +"",
body: json
});
//request header Authorization is added to specify that the request has an authenticated token
request.headers.append('Authorization', 'Bearer ' + this.authService.getToken());
request.headers.append('Content-Type', this.appContent);
request.headers.append('Accept', this.appContent);
return request;
}
else {
console.log('notauthenticated');
this._router.navigateByUrl('/login');
}
}
}
ユーザーリストコンポーネント
import { Component, OnInit,NgZone } from '@angular/core';
import { UserService } from './../../shared/services/user.service';
import { Router } from '@angular/router';
import { AuthService } from './../../shared/services/auth.service';
import { Http, Request, RequestMethod, RequestOptions, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {User} from './../../shared/models/user';
@Component({
selector: 'app-userlist',
templateUrl: './userlist.component.html',
styleUrls: ['./userlist.component.css']
})
export class UserlistComponent implements OnInit {
private appContent = 'application/json';
private baseUrl = 'http://localhost:5000/api/v1/';
private users: User[];
constructor(authService: AuthService, private http: Http,private router: Router, private userService: UserService) {
}
ngOnInit() {
console.log("Test");
this.userService.read().subscribe(
users => this.users = users,
err => {
console.log(err);
}
);
}
editUser(id) {
this.router.navigateByUrl('/users/edit/'+id);
}
}
ユーザーリストテンプレート
<h1 class='text-info' >Users</h1>
<hr>
<div class="container">
<table class="table table-hover table-bordered thead-inverse">
<thead>
<tr class="bg-success">
<th>Client</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users" (click)="editUser(user.id)">
<td>{{user.client}}</td>
<td>{{user.firstName}}</td>
<td >{{user.lastName}}</td>
</tr>
</tbody>
</table>
</div>
誰かが私に助けてくれればと感謝します。
あなたは私にuserService.updateを表示できますか? – bgraham
あなたのユーザーテーブルのコンポーネントコードも表示できますか? – bgraham
お返事いただき、ありがとうございました@bgrahamに必要事項を追加しました –