使用Angular 2更新/ PUT json

时间:2016-12-22 00:42:48

标签: javascript angular

我有更新/ PUT与角度2的问题。我在member-detail.component.ts文件中创建函数updateMember()。函数获取对象并将其发送到服务器,但是当tslint代码时,cosole会返回一些错误:

app/members/member-detail.component.ts(51,42): error TS2345: Argument of type 'Member[]' is not assignable to parameter of type 'Member'. Property '_id' is missing in type 'Member[]'.
app/members/member-detail.component.ts(53,17): error TS7006: Parameter 'res' implicitly has an 'any' type.
app/members/member-detail.component.ts(56,17): error TS7006: Parameter 'error' implicitly has an 'any' type.
  

member.model

export class Member {
constructor(
    public _id: string,
    public name: string,
    public old: number
) { }
}
  

members.service

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Member } from './member';
import { Observable } from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class MembersService {

private apiUrl = 'http://localhost:3000/api/members';

constructor( private http: Http ) { }

...

updateMember(member: Member): Observable<Member[]> {
    let body = JSON.stringify( member );
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.put(`${this.apiUrl}/${member._id}`, body, options)
        .map(this.extractData)
        .catch(this.handleError);
}


private extractData(res: Response) {
    let body = res.json();
    return body.data || {};
}


private handleError (error: Response | any) {

    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;

    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);
    return Observable.throw(errMsg);

}


}
  

构件-detail.component

import { Component, OnInit, Input, trigger, state, style, transition, animate, keyframes } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

import { Observable } from 'rxjs/Observable';

import { Member } from './member';
import { MembersService } from './members.service';

@Component({
moduleId: module.id,
selector: 'member-detail',
templateUrl: 'member-detail.component.html',
styleUrls: [ 'member-detail.component.css' ],
animations: [
    trigger('showContent', [
        transition('void => *', [
            animate(500, keyframes([
                style({opacity: 0, offset: 0}),
                style({opacity: 0.01, offset: 0.99}),
                style({opacity: 1, offset: 1}),
            ]))
        ])
    ])
]
})
export class MemberDetailComponent implements OnInit {

member: Member[];
errorMessage: string;

constructor( private route: ActivatedRoute, private membersService: MembersService ) { }

...

// function update but not tslint correct
updateMember() {
    this.membersService.updateMember(this.member)
        .subscribe(
            res => { 
                this.member = res;
            },
            error =>  this.errorMessage = <any>error
        );
}


}

2 个答案:

答案 0 :(得分:0)

MemberDetailComponent内,您有一个名为member的字段,其类型为Member[],表示array的{​​{1}}

Member

并且您将此作为export class MemberDetailComponent implements OnInit { member: Member[]; <--- 方法的输入

updateMember

但它需要输入类型this.membersService.updateMember(this.member) <---

Member

答案 1 :(得分:0)

我找到解决方案,但它不是很好,所以如果有人有更好的建议分享它!

我在newMember: any;中添加了新变量MemberDetailComponent(),并将对象从this.member引用到newMember并在updateMember()中使用

在我的新代码下面:

  

构件-detail.component.ts

import { Component, OnInit, trigger, state, style, transition, animate, keyframes } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

import { Observable } from 'rxjs/Observable';

import { Member } from './member';
import { MembersService } from './members.service';

@Component({
    moduleId: module.id,
    selector: 'member-detail',
    templateUrl: 'member-detail.component.html',
    styleUrls: [ 'member-detail.component.css' ],
    animations: [
        trigger('showContent', [
            transition('void => *', [
                animate(500, keyframes([
                    style({opacity: 0, offset: 0}),
                    style({opacity: 0.01, offset: 0.99}),
                    style({opacity: 1, offset: 1}),
                ]))
            ])
        ])
    ]
})
export class MemberDetailComponent implements OnInit {
    
    member: Member[];
    errorMessage: string;
    newMember: any; // new variable

    constructor( private route: ActivatedRoute, private membersService: MembersService ) { }

    ngOnInit() { 
        this.getMember();
    }

    getMember(): void {
        this.route.params.subscribe(params => {
            if (params['id'] !== undefined) {
                this.membersService.getMember(params['id'])
                    .subscribe( 
                        member => { this.member = member },
                        error =>  this.errorMessage = <any>error,
                        () => this.newMember = this.member
                    );
            }
        });
    }

    updateMember(): void {
        this.membersService.updateMember(this.newMember)
            .subscribe(
                res => this.newMember = res,
                error =>  this.errorMessage = <any>error,
                () => this.getMember()
            );
    }
    
}