【问题标题】:Cannot set property stack of [object Object] which has only a getter无法设置只有 getter 的 [object Object] 的属性堆栈
【发布时间】:2020-09-10 17:39:12
【问题描述】:

我在以下 plunker 中收到以下错误。

无法设置只有 getter 的 [object Object] 的属性堆栈

Plunker 来了 https://plnkr.co/edit/IP1ssat2Gpu1Cra495u2?p=preview

代码如下:

//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 {}

更新

我能理解错误就在这里

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

如果我评论这 4 行,那么它工作正常。请帮忙。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    如果您想在App 中使用myService,您需要将其分配给构造函数中的属性或指定其可见性(TypeScript 功能):

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

    换句话说,this.myService 在调用 this.myService.getData(myModelObj) 时是未定义的。

    您更新的演示:https://plnkr.co/edit/OyYUDSfD0Q8dDuwEAr1l

    【讨论】:

    • 只有一个私人关键字需要我 2 个小时。 :(
    猜你喜欢
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 2020-09-26
    • 2021-05-31
    • 1970-01-01
    • 2020-08-29
    • 2019-02-24
    • 2020-09-16
    相关资源
    最近更新 更多