2017-10-05 5 views
7

테이블이 각도 2로 업데이트되지 않음

테이블을 클릭하면 내 UsersList 구성 요소입니다. 새 페이지는 사용자 값을 변경하고 저장하면

enter image description here

을 열 수 있습니다, 저장된 값은 처음으로 그리드에 반영되지 않습니다. 그러나 동일한 작업을 다시 수행하면 다시 반영됩니다.

다음은 내 저장 사용자 코드 내가 이해하지 못했다 무엇

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 ("사용자"); 은 관찰 결과에서 응답을받은 후에 호출됩니다. 처음으로 테이블에서 업데이트되지 않는 이유는 무엇입니까?

사용자 - 편집 - 구성 요소

<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> 

누군가가이 문제에 대해 도움을 주시면 감사하겠습니다. 변경

+0

나에게 userService.update를 표시 할 수 있습니까? – bgraham

+0

또한 사용자 테이블의 구성 요소 코드를 볼 수 있습니까? – bgraham

+0

답장을 보내 주신 고마워요 @bgraham이 필요합니다. –

답변

2

시도 :

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"); 
} 

사람 :

async saveUser(){ 
    await this.userService.update(this.user.client,this.user.firstName, 
    this.user.lastName,this.user.id,this.user.key) 
    .toPromise() 
    .then(users => this.user = users) 
    .catch(err => console.log(err)); 
    this.router.navigateByUrl("users"); 
} 

또는 : 나는 또한 같은 문제에 직면했다

saveUser(){ 
    this.userService.update(this.user.client,this.user.firstName, 
    this.user.lastName,this.user.id,this.user.key).subscribe(
    users => { 
     this.user = users; 
     this.router.navigateByUrl("users"); 
     }, 
     err => { 
     console.log(err); 
     } 
    );    
} 
+0

작동하지 않았습니까? –

1

. 저를 위해 일한 것은 사용자의 세부 정보를 성공적으로 저장하면 전체 사용자 목록을 가져 오는 서비스의 함수를 호출했기 때문입니다. 이렇게하면 사용자 목록이 최신으로 업데이트되었습니다.

그래서 saveUser 함수에서 userService의 업데이트 기능 후 userService의 read 함수를 호출하십시오. 사용자 목록을 업데이트해야합니다.

0

아마도 경로가 동일하므로 Angular가 구성 요소를 재사용하고 있으므로 ngOnInit을 다시 실행하지 않을 수 있습니까? 다음

ngAfterViewInit() { 

    console.log("Test"); 
    this.userService.read().subscribe(
     users => this.users = users, 

     err => { 
     console.log(err); 
     } 
    ); 
    } 

당신이 당신의 ngOnInit 후크에서 경로 변경 이벤트에 가입하는 것입니다 시도 할 수 있었다 또 다른 접근을하고,이 같은 대신 ngOnInit의 ngOnChanges 또는 ngAfterViewInit 후크에 userlist.component에 사용자로드 논리를 배치하십시오 데이터를 새로 고칩니다. 이 답변에 대한 답변과 같은 것 question :

this.router.events.subscribe((event) => { 
// your refresh logic 
} 
관련 문제