Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set property stack of [object Object] which has only a getter

I am getting the following error in the following plunker.

Cannot set property stack of [object Object] which has only a getter

Plunker is here https://plnkr.co/edit/IP1ssat2Gpu1Cra495u2?p=preview

Code is as follows:

//our root app component
import {Component, NgModule, OnInit, Injectable} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { HttpModule, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

class MyModel {
  public name: string;
  public value: string;
}

@Injectable()
export class MyService {

  constructor(public http: Http) {

  }

  getData (request: MyModel):Promise<MyModel>{
    return this.http.get('https://run.plnkr.co/j2Cw0yaD5Dn7ENaR/mymodel.json')
                .toPromise()
                .then(response => {
                                return response as MyModel;
                        });
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App implements AfterViewInit {
  name:string;

  constructor(myService : MyService) {
    this.name = 'Angular2'
  }

  ngAfterViewInit(){

    let myModelObj : MyModel = new MyModel();
    console.log(this.myService);
    this.myService.getData(myModelObj)
      .then(response => {
        console.log('GET Request success')
        console.log(response);
      });

  }
}

@NgModule({
  imports: [ BrowserModule, HttpModule ],
  declarations: [ App ],
  providers : [MyService],
  bootstrap: [ App ]
})
export class AppModule {}

Update

I am able to understand the error is here

this.myService.getData(myModelObj)
          .then(response => {
            console.log('GET Request success')
            console.log(response);
          });

If I comment this 4 lines then it is working fine. Please help.

like image 243
Partha Sarathi Ghosh Avatar asked Jan 13 '17 13:01

Partha Sarathi Ghosh


Video Answer


1 Answers

If you want to use myService in App you need to either assign it to a property in the constructor or specify its visibility (TypeScript feature):

constructor(private myService : MyService) {
    this.name = 'Angular2'
}

In other words this.myService is undefined when calling this.myService.getData(myModelObj).

Your updated demo: https://plnkr.co/edit/OyYUDSfD0Q8dDuwEAr1l

like image 112
martin Avatar answered Oct 26 '22 01:10

martin