簡體   English   中英

錯誤 TypeError:無法讀取未定義的屬性(讀取“getProfile”)

[英]ERROR TypeError: Cannot read properties of undefined (reading 'getProfile')

我正在嘗試將本地 json 文件中的數據顯示到 angular 12 的表中,但第一步我只想控制該文件中的數據。 但是我發現了我在標題中寫的錯誤。 這是我的代碼:app.module.ts:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import {MaterialExampleModule} from '../material.module';
import {TablePaginationExample} from './table-pagination-example';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatNativeDateModule} from '@angular/material/core';
import {HttpClientModule} from '@angular/common/http';

@NgModule({
  declarations: [TablePaginationExample],
  imports: [
    BrowserAnimationsModule,
    BrowserModule,
    FormsModule,
    HttpClientModule,
    MatNativeDateModule,
    MaterialExampleModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [TablePaginationExample],
})
export class AppModule {}

表分頁example.ts:

import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator} from '@angular/material/paginator';
import {MatTableDataSource} from '@angular/material/table';
import { ServerHttpService } from './Services/server-http.service';

/**
 * @title Table with pagination
 */
@Component({
  selector: 'table-pagination-example',
  styleUrls: ['table-pagination-example.css'],
  templateUrl: 'table-pagination-example.html',
})
export class TablePaginationExample implements OnInit {

  private serverHttp: ServerHttpService;
  displayedColumns: string[] = ['secCd', 'secType', 'secSName', 'secName', 'capitalValue', 'listedQty', 'foreignMaxQty', 'stockDividendRate', 'cashDividendRate', 'marketCd', 'tradingLot', 'parValue', 'maxRoom', 'status', 'remarks'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit(): void {
    this.dataSource.paginator = this.paginator;
    this.serverHttp.getProfile().subscribe((data) => {
      console.log(data);
    })
  }
  
}

export interface PeriodicElement {
  // action: string,
  // secCd: string,
  // secType: string,
  // secSName: string,
  // secName: string,
  // capitalValue: number,
  // listedQty: number,
}

const ELEMENT_DATA: PeriodicElement[] = []

服務器-http.service.ts:

import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable } from 'rxjs';
import { throwError } from 'rxjs/internal/observable/throwError';

@Injectable({
  providedIn: 'root'
})

export class ServerHttpService {

  private httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    }),
  }
  
  private REST_API_SERVER = 'http://localhost:3000'

  constructor(private httpClient: HttpClient) { }

  public getProfile(): Observable<any> {
    const url = `${this.REST_API_SERVER}/profile`;
    return this.httpClient
      .get<any>(url, this.httpOptions)
      .pipe(catchError(this.handleError));
  }

  private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, body was: `, error.error);
    }
    // Return an observable with a user-facing error message.
    return throwError(() => new Error('Something bad happened; please try again later.'));
  }
}

這是控制台屏幕的圖片: image

感謝您的關注,如果我的問題或我的英語有任何問題,請告訴我。 這是我第一次向 Stackoverflow 發帖提問。

你必須刪除private serverHttp: ServerHttpService; 並改為添加以下代碼。

constructor(private serverHttp: ServerHttpService) {}

您可以在此處詳細了解 Angular 服務的依賴注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM