将对象传递给子组件Angular2

时间:2018-02-05 09:09:03

标签: angular typescript

从订阅中获取数据时,我的数据没有绑定到我的本地变量。

我有两个组件和一个服务。父组件调用从服务到http get的方法,get包括我需要绑定的用户对象。 但是,当console.logging对象超出订阅时,它似乎未定义。

这是我的代码:

父组件:

selectedUser : User;
  onUserRowSelect(event): void {
    this.router.navigate(['../childComponent'], { relativeTo: this.route });

    this.formService.getUser(event.data.USER_ID).subscribe(result => {
      console.log(result); // <-- Object is logged properly.
      this.selectedUser = result; // Assigning the local @Input variable to the result
    });
  }

子组件:

  @Input() selectedUser : User;

      ngOnInit() {
        console.log(this.selectedUser); // Returns undefined.
      }

使用Http服务:

getUser(id: number): Observable<User> {
    const _url = 'myURL/getuser/' + id;
    const headers = new Headers();
    headers.append('X-User', sessionStorage.getItem('username'));
    headers.append('X-Token', sessionStorage.getItem('token'));
    headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
    headers.append('Content-Type', 'application/json');
    const options = new RequestOptions({ headers: headers });

    return this.http.get(_url, options)
        .map(response => {
            const responseAsObject = response.json();
            this.myUser = responseAsObject;
            return responseAsObject;
        });
}

HTML表单模板:

儿童模板

<div id="top">
    <nb-card>
        <nb-card-header>Update User</nb-card-header>
        <nb-card-body header="Update User">
            <div class='row'>
                <div class='col-md-6'>
                    <form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
                        <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['username'].valid}">
                            <label>Username</label>
                            <input [(ngModel)]="username" class="form-control" id="username" type="text" [formControl]="complexForm.controls['username']">
                        </div>
                        <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['group_id'].valid}">
                            <label>Group ID</label>
                            <div class="row" *ngIf="roles.length">
                                <div class="col-md-4">
                                    <select [(ngModel)]="selectedGroup" name="group_id" (change)="onChange($event)" class="form-control" [formControl]="complexForm.controls['group_id']"
                                        data-width='200px'>
                                        <option [ngValue]="role.GROUP_ID" *ngFor="let role of roles">
                                            {{role.NAME}}
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>First Name</label>
                            <input [(ngModel)]="fname" class="form-control" type="text" [formControl]="complexForm.controls['fname']">
                        </div>
                        <div class="form-group">
                            <label>User ID</label>
                            <input [(ngModel)]="ID" class="form-control" type="text" [formControl]="complexForm.controls['USER_ID']">
                        </div>
                        <div class="form-group">
                            <label>Last Name</label>
                            <input [(ngModel)]="lname" class="form-control" type="text" [formControl]="complexForm.controls['lname']">
                        </div>
                        <div class="form-group">
                            <label>Organization</label>
                            <input [(ngModel)]="organization" class="form-control" type="text" [formControl]="complexForm.controls['organization']">
                        </div>
                        <div class="form-group">
                            <label>Phone</label>
                            <input [(ngModel)]="phone" class="form-control" type="text" [formControl]="complexForm.controls['phone']">
                        </div>
                        <div class="form-group">
                            <label>Creation Date</label>
                            <input [(ngModel)]="creationDate" class="form-control" type="text" [formControl]="complexForm.controls['creation_date']">
                        </div>
                        <div class="form-group">
                            <label>Last Login</label>
                            <input [(ngModel)]="lastLogin" class="form-control" type="text" [formControl]="complexForm.controls['last_login']">
                        </div>
                        <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['status'].valid}">
                            <label>Status</label>
                            <div class="row" *ngIf="statuses.length">
                                <div class="col-md-6">
                                    <select [(ngModel)]="selectedStatus" name="stasus" (change)="onChange($event)" class="form-control" [formControl]="complexForm.controls['status']"
                                        data-width='500px'>
                                        <option [ngValue]="status.STATUS" *ngFor="let status of statuses">
                                            {{status.STATUS_DESC}}
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Logged In</label>
                            <input [(ngModel)]="loggedIn" class="form-control" type="text" [formControl]="complexForm.controls['logged_in']">
                        </div>
                        <div class="form-group">
                            <label>Password Bad Tries</label>
                            <input [(ngModel)]="pwdBadTries" class="form-control" type="text" [formControl]="complexForm.controls['pwd_badtries']">
                        </div>
                        <div class="form-group">
                            <label>Title</label>
                            <input [(ngModel)]="title" class="form-control" type="text" [formControl]="complexForm.controls['title']">
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input [(ngModel)]="email" class="form-control" type="text" [formControl]="complexForm.controls['email']">
                        </div>
                        <div class="form-group">
                            <label>User Expiry in Days</label>
                            <input [(ngModel)]="userExpiryInDays" class="form-control" type="text" [formControl]="complexForm.controls['user_expiry_in_days']">
                        </div>
                        <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['restricted_ip'].valid}">
                            <label>Restricted IP</label>
                            <input [(ngModel)]="restrictedIp" class="form-control" type="text" [formControl]="complexForm.controls['restricted_ip']">
                            <div *ngIf="complexForm.controls['restricted_ip'].hasError('pattern') && complexForm.controls['restricted_ip'].touched" class="alert alert-danger">Not a valid IP Address.</div>
                        </div>
                        <div class="form-group">
                            <label>Password Expiry Date</label>
                            <input [(ngModel)]="pwdExpdate" class="form-control" type="text" [formControl]="complexForm.controls['pwd_expdate']">
                        </div>
                        <div class="form-group">
                            <button type="submit" value="update" [disabled]="!complexForm.valid" class="btn btn-success">Update User</button>
                        </div>
                    </form>
                    <div>
                        <button type="submit" value="delete" class="btn btn-success" (click)="confirmDelete()">Delete User</button>
                    </div>
                    <br/>
                    <div>
                        <button type="submit" value="delete" class="btn btn-success" (click)="getNewPassword()">Set Password</button>
                    </div>
                </div>
            </div>
        </nb-card-body>
    </nb-card>

父HTML:

    <div>
    <div class="row-md-6">
        <nb-card title="List of Users">
            <ng2-smart-table [settings]="settings" [source]="source" (userRowSelect)="onUserRowSelect($event)"></ng2-smart-table>
        </nb-card>
    </div>
</div>

父组件是用户列表,子组件是用于编辑所选用户的表单菜单,因为我想将用户传递给子组件进行编辑

所以我的问题在于,即使在将@input装饰器添加到变量之后,selectedUser在子组件中也显示为未定义。

2 个答案:

答案 0 :(得分:0)

<ng2-smart-table [settings]="settings" [source]="source" (userRowSelect)="onUserRowSelect($event)" [selectedUser]="selectedUser"></ng2-smart-table>

有关详细信息,请参阅https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

答案 1 :(得分:0)

1-在服务类中创建类型为user的变量 public selectedUser: user;

2-在父组件onUserRowSelect(user: User) this.yourService.selectedUSer = user this.router.navigate(['***']);

3-在子组件中

Console.log(this.yourService.selectedUSer);