locked
Help required in inserting data in db and viewing in grid with angular2 RRS feed

  • Question

  • User483994611 posted

    My UI has some text boxes and on clicking on submit button data will be inserted in db and data will be displayed in grid

    I can see data is returned from web api but grid is not populated..plz help what I am doing wrong?

    Secondly Error TS2693 'StudentMasters' only refers to a type, but is being used as a value here.

    from the below code marked in bold:-

    getData() {
    this.http.get('api/StudentMastersAPI')
    .map((responseData) => {
    return responseData.json();
    })
    .map((student: Array<any>) => {
    let result: Array<StudentMasters> = [];
    if (student) {
    student.forEach((student) => {
    result.push(new StudentMasters(student.StdID, student.StdName,
    student.Email, student.Phone, student.Address));
    });
    }
    return result;
    })
    .subscribe(res => this.student = res);

    }

    Please suggest what I am doing wrong

    My entire Registration.component.ts looks like

    import { Component, Injectable, Inject } from '@angular/core';

    import { NgIf, NgFor } from '@angular/common';
    import { Http, Response, Headers, RequestOptions } from '@angular/http';



    @Component({
    selector: "registration"

    , template: require('./Registration.component.html')

    })
    export class RegistrationComponent {

    students = {};

    public student: StudentMasters[] = [];
    myName: string; 
    constructor(@Inject(Http) public http: Http) {
    this.myName = "Shanu"; 
    this.getData(); 
    }

    getData() { 
    this.http.get('api/StudentMastersAPI')
    .map((responseData) => {
    return responseData.json();
    })
    .map((student: Array<any>) => {
    let result: Array<StudentMasters> = [];
    if (student) {
    student.forEach((student) => {
    result.push(new StudentMasters(student.StdID, student.StdName,
    student.Email, student.Phone, student.Address));
    });
    }
    return result;
    }) 
    .subscribe(res => this.student = res);

    //this.http.get('/api/StudentMastersAPI/Student').subscribe(result => {
    // this.student = result.json();
    //});
    }

    addStudentsDetails() { 
    var headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-8');
    this.http.post('api/StudentMastersAPI', JSON.stringify(this.students), { headers: headers }).subscribe();
    alert("Student Detail Inserted");
    this.getData(); 
    }


    }
    export interface StudentMasters {
    stdID: number;
    stdName: string;
    email: string;
    phone: string;
    address: string;
    }

    Tuesday, September 12, 2017 9:59 AM

All replies

  • User521776492 posted

    tengo el mismo problema y no logro resolverlo. Cry , alguien que pueda ayudar ??? Se agradece desde ya.

    Tuesday, September 12, 2017 11:47 AM
  • User-1508012637 posted

    Hi, 

    Please try the following code:

    getData(): void {
        this._http.get('api/StudentMastersAPI')
            .map((responseData: Response) => <StudentMasters[]>responseData.json())
            .subscribe(res => this.student = res);
    }

    And remember to import rxjs module:

    import 'rxjs/add/operator/map';

    If you have any other questions, please feel free to contact me any time.

    Best Regards
    Velen

    Wednesday, September 13, 2017 3:21 AM
  • User483994611 posted

    I noticed grid has been constructed with blank rows not sure why it is happening

    The entire html looks lke

    <p *ngIf="!student"><em>Loading Student Details please Wait ! ...</em></p>

    <table style="background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding :5px;width :99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="student">

        <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">

            <td>

                <h2>Insert Student Details : </h2>

            </td>

        </tr>

        <tr>

            <td>

                <table style="color:#9F000F;font-size:large" cellpadding="4" cellspacing="6">

                    <tr>

                        <td><b>Students ID: </b> </td>

                        <td>

                            <input [(ngModel)]="students.StdID" value="0" style="background-color:tan" readonly>

                        </td>

                        <td><b>Students Name: </b> </td>

                        <td>

                            <input [(ngModel)]="students.StdName">

                        </td>

                    </tr>

                    <tr>

                        <td><b>Email: </b> </td>

                        <td>

                            <input [(ngModel)]="students.Email">

                        </td>

                        <td><b>Phone: </b> </td>

                        <td>

                            <input [(ngModel)]="students.Phone">

                        </td>

                    </tr>

                    <tr>

                        <td><b>Address: </b> </td>

                        <td>

                            <input [(ngModel)]="students.Address">

                        </td>

                        <td colspan="2">

                            <button (click)=addStudentsDetails() style="background-color:#334668;color:#FFFFFF;font-size:large;width:200px;

                                  border-color:#a2aabe;border-style:dashed;border-width:2px;">

                                Save

                            </button>

                        </td>

                    </tr>

                </table>

            </td>

        </tr>

        <tr><td>&nbsp; </td></tr>

        <tr>

            <td>

                <table style="background-color:#FFFFFF; border:solid 2px #6D7B8D; padding: 5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2">

                    <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">

                        <td width="100" align="center">Student ID</td>

                        <td width="240" align="center">Student Name</td>

                        <td width="240" align="center">Email</td>

                        <td width="120" align="center">Phone</td>

                        <td width="340" align="center">Address</td>

                    </tr>

                    <tbody *ngFor="let std of student">

                        <tr>

                            <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">

                                <span style="color:#9F000F">{{std.StdID}}</span>

                            </td>

                            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">

                                <span style="color:#9F000F">{{std.StdName}}</span>

                            </td>

                            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">

                                <span style="color:#9F000F">{{std.Email}}</span>

                            </td>

                            <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">

                                <span style="color:#9F000F">{{std.Phone}}</span>

                            </td>

                            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">

                                <span style="color:#9F000F">{{std.Address}}</span>

                            </td>

                        </tr>

                    </tbody>

                </table>

            </td>

        </tr>

    </table>

    <table style="background-color:#FFFFFF; border:solid 2px #6D7B8D; padding: 5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2">
                    <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">                    <td width="100" align="center">Student ID</td>                    <td width="240" align="center">Student Name</td>                    <td width="240" align="center">Email</td>                    <td width="120" align="center">Phone</td>                    <td width="340" align="center">Address</td>

                    </tr>                <tbody *ngFor="let std of student">                    <tr>
                            <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">                            <span style="color:#9F000F">{{std.StdID}}</span>                        </td>
                            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">                            <span style="color:#9F000F">{{std.StdName}}</span>                        </td>
                            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">                            <span style="color:#9F000F">{{std.Email}}</span>                        </td>
                            <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">                            <span style="color:#9F000F">{{std.Phone}}</span>                        </td>
                            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">                            <span style="color:#9F000F">{{std.Address}}</span>                        </td>
                        </tr>                </tbody>            </table>

    Wednesday, September 13, 2017 6:02 AM
  • User-1508012637 posted

    Hi,

    I've made a little change to your code and the data could be displayed. The screenshot as below:

    Please refer to the following revised code:

    Registration.component.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <table style="background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding :5px;width :99%;table-layout:fixed;" cellpadding="2"
               cellspacing="2" *ngIf="student">
            <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                <td>
                    <h2>Insert Student Details : </h2>
                </td>
            </tr>
    
            <tr>
                <td>
                    <table style="color:#9F000F;font-size:large" cellpadding="4" cellspacing="6">
                        <tr>
                            <td><b>Students ID: </b> </td>
                            <td>
                                <input [(ngModel)]="students.StdID" value="0" style="background-color:tan" readonly>
                            </td>
                            <td><b>Students Name: </b> </td>
    
                            <td>
                                <input [(ngModel)]="students.StdName">
                            </td>
                        </tr>
    
                        <tr>
                            <td><b>Email: </b> </td>
                            <td>
                                <input [(ngModel)]="students.Email">
                            </td>
                            <td><b>Phone: </b> </td>
                            <td>
                                <input [(ngModel)]="students.Phone">
                            </td>
    
                        </tr>
                        <tr>
                            <td><b>Address: </b> </td>
                            <td>
                                <input [(ngModel)]="students.Address">
                            </td>
    
                            <td colspan="2">
                                <button (click)=addStudentsDetails() style="background-color:#334668;color:#FFFFFF;font-size:large;width:200px;
                                          border-color:#a2aabe;border-style:dashed;border-width:2px;">
                                    Save
                                </button>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
    
            <tr>
                <td>&nbsp; </td>
            </tr>
    
            <tr>
                <td>
                    <table style="background-color:#FFFFFF; border:solid 2px #6D7B8D; padding: 5px;width:99%;table-layout:fixed;" cellpadding="2"
                           cellspacing="2">
                        <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                            <td width="100" align="center">Student ID</td>
                            <td width="240" align="center">Student Name</td>
                            <td width="240" align="center">Email</td>
                            <td width="120" align="center">Phone</td>
                            <td width="340" align="center">Address</td>
                        </tr>
    
                        <tbody>
                            <tr *ngFor="let std of student">
                                <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                    <span style="color:#9F000F">{{std.StdID}}</span>
                                </td>
    
                                <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                    <span style="color:#9F000F">{{std.StdName}}</span>
                                </td>
    
                                <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                    <span style="color:#9F000F">{{std.Email}}</span>
                                </td>
    
                                <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                    <span style="color:#9F000F">{{std.Phone}}</span>
                                </td>
    
                                <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                    <span style="color:#9F000F">{{std.Address}}</span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </table>
    </body>
    </html>

    Registration.component.ts

    import { Component, Injectable, Inject, OnInit } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { Http, Response } from '@angular/http';
    import 'rxjs/add/operator/map';
    
    @Component({
        selector: "registration",
        templateUrl: 'app/Test/Registration.component.html' //it's my path, you could change
    })
    export class RegistrationComponent implements OnInit {
    
        ngOnInit(): void {
            this.getData();
        }
    
        students = {};
    
        student: IStudentMasters[];
    
        myName: string;
    
        constructor(public http: Http) {
            this.myName = "Shanu";
        }
    
        getData() {
            this.http.get('http://localhost:*port number*/api/StudentMastersAPI')
                .map((response: Response) => <IStudentMasters[]>response.json())
                .subscribe(
                studentData => this.student = studentData); 
        }
    }
    
    export interface IStudentMasters {
        StdID: number;
        StdName: string;
        Email: string;
        Phone: string;
        Address: string;
    }
    
    export class StudentMasters implements IStudentMasters {
        constructor(public StdID: number, public StdName: string, public Email: string, public Phone: string, public Address: string ) { }
    }
    

    There're several tips for you here:

    1. Remember to implement the interface with a class, because you cannot new a interface directly.

    2. Notice the case in your model's property of your Web API application should match the model's property in you Angular2 application.

    3. You'd better achieve the data in ngOnInit() method instead of the constructor. see: https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit 

    If you have any other questions, please feel free to contact me any time.

    Best Regards
    Velen

    Wednesday, September 13, 2017 9:52 AM
  • User483994611 posted

    I tried your way but I am getting unusual error 

    Unhandled Promise rejection: Component RegistrationComponent is not part of any NgModule or the module has not been imported into your module. ; Zone: <root> ; Task: Promise.then ; Value: ZoneAwareError Error: Component RegistrationComponent is not part of any NgModule or the module has not been imported into your module.
    at JitCompiler._createCompiledHostTemplate (http://localhost:54199/node_modules/@angular/compiler/bundles/compiler.umd.js:27462:23) [<root>]
    at eval (http://localhost:54199/node_modules/@angular/compiler/bundles/compiler.umd.js:27428:41) [<root>]
    at Array.forEach (<anonymous>) [<root>]
    at eval (http://localhost:54199/node_modules/@angular/compiler/bundles/compiler.umd.js:27426:49) [<root>]
    at Array.forEach (<anonymous>) [<root>]
    at JitCompiler._compileComponents (http://localhost:54199/node_modules/@angular/compiler/bundles/compiler.umd.js:27415:47) [<root>]
    at createResult (http://localhost:54199/node_modules/@angular/compiler/bundles/compiler.umd.js:27313:23) [<root>]
    at Zone.run (http://localhost:54199/node_modules/zone.js/dist/zone.js:126:43) [<root> => <root>]
    at http://localhost:54199/node_modules/zone.js/dist/zone.js:713:57 [<root>]
    at Zone.runTask (http://localhost:54199/node_modules/zone.js/dist/zone.js:166:47) [<root> => <root>]
    at drainMicroTaskQueue (http://localhost:54199/node_modules/zone.js/dist/zone.js:546:35) [<root>]
    at XMLHttpRequest.ZoneTask.invoke (http://localhost:54199/node_modules/zone.js/dist/zone.js:424:25) [<root>]
    consoleError @ zone.js:522
    zone.js:524 ZoneAwareError

    My app.module looks like 

    import { NgModule } from '@angular/core';
    import { APP_BASE_HREF } from '@angular/common';
    import { BrowserModule } from '@angular/platform-browser';
    import { ReactiveFormsModule } from '@angular/forms';
    import { AppComponent } from './app.component';
    import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
    import { HttpModule } from '@angular/http';
    import { routing } from './app.routing';
    import { UserComponent } from './components/user.component';
    import { HomeComponent } from './components/home.component';
    import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
    import { RegistrationComponent } from './components/Registration/Registration.component';

    import { UserService} from './Service/user.service'

    @NgModule({
    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],

    declarations: [AppComponent, UserComponent, HomeComponent, FetchDataComponent, RegistrationComponent],

    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, UserService],
    bootstrap: [AppComponent]

    })
    export class AppModule { }

    My app.routing.ts looks like 

    import { ModuleWithProviders } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';

    import { UserComponent } from './components/user.component';
    import { HomeComponent } from './components/home.component';
    import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
    import { RegistrationComponent } from './components/Registration/Registration.component';

    const appRoutes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'user', component: UserComponent }
    , { path: 'fetchdata', component: FetchDataComponent }
    , { path: 'Registration', component: RegistrationComponent }
    ];

    export const routing: ModuleWithProviders =
    RouterModule.forRoot(appRoutes);

    My Registration.component.ts looks like 

    import { Component, Injectable, Inject, OnInit } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    //import { Http, Response } from '@angular/http';
    import 'rxjs/add/operator/map';

    import { NgIf, NgFor } from '@angular/common';
    import { Http, Response, Headers, RequestOptions } from '@angular/http';
    import { FormsModule } from '@angular/forms';
    @Component({
    selector: "registration",


    templateUrl: 'app/Components/Registration/Registration.component.html'
    })
    export class RegistrationComponent implements OnInit {

    ngOnInit(): void {
    alert('hi');
    this.getData();
    }

    students = {};

    student: IStudentMasters[];

    myName: string;

    constructor(public http: Http) {
    this.myName = "Shanu";
    }

    getData() {


    this.http.get('/api/StudentMastersAPI/Student')
    .map((response: Response) => <IStudentMasters[]>response.json())
    .subscribe(
    studentData => this.student = studentData);
    // alert(this.student);

    }

    addStudentsDetails() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-8');
    this.http.post('api/StudentMastersAPI', JSON.stringify(this.students), { headers: headers }).subscribe();
    alert("Student Detail Inserted");
    this.getData();
    }

    }

    export interface IStudentMasters {
    StdID: number;
    StdName: string;
    Email: string;
    Phone: string;
    Address: string;
    }

    export class StudentMasters implements IStudentMasters {
    constructor(public StdID: number, public StdName: string, public Email: string, public Phone: string, public Address: string) { }
    }

    Plz suggest where I am doing wrong

    Monday, November 6, 2017 4:52 AM