Angular表单组件不会将结果追加到列表组件的数组中

时间:2018-02-20 02:30:41

标签: angular

有两个单独的组件usersuser-form

目标

目标是使用user-form发布user,这意味着将其添加到数据库中,然后在users html中显示。

问题

为什么addUser(user: User)没有将新用户添加到现有的users数组中?来自console.log(this.users)组件的users时,没有任何更改。

ExpressJS用户/帖子

这基本上为用户创建了一个新条目,然后使用另一个查询来查找它刚刚创建的用户(因此它可以获取它的id号)。

router.post('/post', (req, res) => {
    var name = req.body.name;
    var email = req.body.email;
    var password = req.body.password;

    var query = `INSERT INTO ${table} VALUES (null, "${name}", "${email}", "${password}")`;
    console.log(query);

    conn.query(query, (err, result, fields) => {
        if (err) throw err;

        query = `SELECT * FROM ${table} WHERE name LIKE '%${name}%' AND email LIKE '${email}'`;
        conn.query(query, (err, result, fields) => {
            if (err) throw err;
            res.send(result[result.length - 1]);
        });
    });
});

用户表单组件html

此表单收集用户的输入并使用onSubmit()提交。

<form (ngSubmit)="onSubmit()" #userForm="ngForm" role="form">
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name"
               [(ngModel)]="user.name" name="name"
               required>
    </div>
    <div class="form-group">
        <label for="email">Email address:</label>
        <input type="email" class="form-control" id="email"
               [(ngModel)]="user.email" name="email"
               required>
    </div>
    <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd"
               [(ngModel)]="user.password" name="password"
               required>
    </div>
    <div class="checkbox">
        <label><input type="checkbox"> Remember me</label>
    </div>
    <button type="submit" class="btn btn-block btn-success" [disabled]="!userForm.form.valid">Submit</button>

</form>

用户表单组件

    import {Component, OnInit} from '@angular/core';
import {User} from "../user";
import {UserService} from "../user.service";
import {UsersComponent} from "../users/users.component";

@Component({
    selector: 'app-user-form',
    templateUrl: './user-form.component.html',
    styleUrls: ['./user-form.component.css'],
    providers: [UsersComponent]
})
export class UserFormComponent implements OnInit {

    user = new User(null, "Ra", "jim@gmail.com", "jimPass");
    submitted = false;

    constructor(private userService: UserService, private usersComponent: UsersComponent) {
    }

    ngOnInit() {
    }

    get diagnostic() {
        return JSON.stringify(this.user);
    }

    onSubmit() {
        this.submitted = true;
        this.addUser(this.user);
        console.log("UserFormComponent.onSubmit(): ", this.user);
    }

    clear() {
        this.user = new User(null, "", "", "");
    }

    addUser(user: User): void {
        this.userService.postUserObject(user)
            .subscribe(
                res => {
                    console.log("addUser() next: ", res);
                    this.usersComponent.appendUser(res);
                },
                err => console.error("addUser() error: ", err),
                () => {
                    console.log("addUser() loaded: ", user);

                }
            );
        this.usersComponent.check("Some msg");
    }
}

用户组件

    import {Component, Input, NgZone, OnInit} from '@angular/core';

import {User} from "../user";
import {UserService} from "../user.service";

@Component({
    selector: 'app-users',
    templateUrl: './users.component.html',
    styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
    users: User[];

    constructor(private zone: NgZone, private userService: UserService) {
        this.users = [];
    }

    ngOnInit() {
        this.getUsers();
        //let timer = Observable.timer(2000, 5000);
        //timer.subscribe(() => this.getUsers());
    }

    getUsers(): void {
        this.userService.getUsers()
            .subscribe(
                users => {
                    this.zone.run(() => this.users = users)
                },
                error => console.error(error),
                () => console.log("Users: ", this.users)
            );
    }

    appendUser(user: User): void {
        console.log("UsersComponent.appendUser(): ", user);
        this.zone.run(() => this.users.push(user));
    }

    logUsers(): void {
        console.log("logUsers(): ", this.users);
    }

    check(msg: string): void {
        console.log("check(): ", msg);
    }
}

用户html

    <ul *ngIf="users.length > 0" class="users">
    <li *ngFor="let user of users">
        {{user.name}}
    </li>
</ul>

Angular app github link

ExpressJS app github link

2 个答案:

答案 0 :(得分:0)

添加到数组后需要放置console.log,而不必明确提及this.zone.run(),试试,

appendUser(user: User): void {
    this.users.push(user);
    console.log("UsersComponent.appendUser(): ", this.users);
}

也将console.log放在subscribe

this.userService.getUsers()
            .subscribe(
                users => {
                   this.users = users;
                   console.log("Users: ", this.users)
                },
                error => console.error(error) 
            );

答案 1 :(得分:0)

我认为如果它们位于单独的页面和单独的路径上,您应该在添加成功后重定向到用户组件。无需使用NgZone,也无需注入用户组件。