【问题标题】:Uncaught (in promise): TypeError: Cannot read property 'get' of undefined in angular2+未捕获(承诺中):TypeError:无法读取 angular2+ 中未定义的属性“get”
【发布时间】:2019-02-08 09:45:29
【问题描述】:

我在 angular2+ 文件中制作了一个组件。我想向 nodeJs 服务器发出一个 http 请求。但是,我不断得到->

Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined

请注意,我什至无法检索存储在一个函数中并且(无法)在另一个函数中访问的全局变量的值。这是我第一次面对它。

代码-

app.component.ts

import { HttpClient, HttpParams, HttpRequest, HttpEvent } from '@angular/common/http';

@Injectable()
export class MachineMergerComponent implements OnInit {

    constructor(private http: HttpClient) {}

    onFileLoadTopFive(fileLoadedEvent) {

        // -----===================  Top Five Neovis  ==================== -------------

        this.rhsNameTopFive = [];
        this.relationshipInfo = [];

        for (var i = 0; i < 5; i++) {

            this.rhsNameTopFive.push(this.objectValueAfterConfidence1[i].rhs[0])

            console.log("this.rhsNameTopFive = ", this.rhsNameTopFive)

            // http request

            var relationObj = {
                'relationObj1': this.rhsNameTopFive[i]
            }

        }
        console.log("relationObj = ", relationObj);


        this.http.get("http://localhost:3003/seekRelationship?relationObj=" + this.rhsNameTopFive[0])
            .map(Response => Response)
            .catch((err) => {
                console.log("err =", err)
                return Observable.throw(err);

            })
            .subscribe((res: Response) => {

                console.log("XXXXXXXXXXXX Response on /seekExtraction", res);

                this.relationshipInfo[i] = res;

                console.log(" this.relationshipInfo[" + i + "]", this.relationshipInfo[i])
            })
    }

}

app.module.ts

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    CommonModule,

    FormsModule,
    // HttpModule ,

    HttpClientModule,

  ],
  declarations: [   MachineMergerComponent,  ]
})
export class ApiSequenceModule { }

【问题讨论】:

  • 使用返回类型编写 API 调用服务以获得最佳实践并在组件中订阅
  • 您是否将服务添加到主目录
  • 你对组件和服务有混淆吗?
  • 是的 .... 这是一个组件,其中我有很多代码、文件上传代码和 http 请求也是我想要的。

标签: angular http get angular-httpclient


【解决方案1】:

MachineMergerComponent 是一项服务。将其添加到提供者列表下。 (也可以考虑将其重命名为 MachineMergerService )

declarations: [  ... ],
providers:    [ MachineMergerComponent ]

【讨论】:

  • 另一个选项,取决于 Angular 版本,是添加@Injectable({ providedIn: 'root' })。这使它成为一个不必在提供者部分注册的单例。
  • @Sachila... 我收到错误 -> 组件 MachineMergerComponent 不是任何 NgModule 的一部分,或者该模块尚未导入您的模块。错误:组件 MachineMergerComponent 不是任何 NgModule 的一部分,或者该模块尚未导入到您的模块中。
猜你喜欢
  • 2019-05-16
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 2021-03-07
  • 1970-01-01
  • 2018-06-03
  • 2020-09-24
相关资源
最近更新 更多