没有使用@Input装饰器Angular2传递对象

时间:2018-02-07 14:04:06

标签: angular

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

我有两个组件和一个服务。父组件调用从服务到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;
        });
}

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

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

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

3 个答案:

答案 0 :(得分:0)

真的很老的问题,但这里的答案是构造函数上不存在输入,但它最终会存在。使用ngOnInit查看输入。

class ChildComponent implements OnInit {
  ngOnInit() {
    console.log(changes.selectedUser);
  }
  ...
}

答案 1 :(得分:-1)

你孩子的onInit过早执行。添加ngOnChanges方法并记录所有更改。您应该看到,稍后在父级中可用时,它也会在子级上更新。

class ChildComponent implements OnChanges {
  ngOnChanges(changes: SimpleChanges) {
    console.log(changes.selectedUser);
  }
  ...
}

请注意,您不需要ngOnChanges来获取它们。只有在您想要明确做出反应时才会这样。您可以简单地准备组件,使其在没有选定的用户可用之前工作(或者用例如ngIf隐藏它)。

答案 2 :(得分:-1)

查看此示例:https://plnkr.co/edit/zn1Xagi0J1TxPxTBAl3M?p=preview

使用ngOnChanges

如果它没有记录任何内容,则表示其他地方存在问题。

您是否正确通过了selectedUser[selectedUser]="selectedUser"

也可能不会触发更改,因为旧的selectedUser具有相同的引用。但如果它在开始时是null,则不是问题。