ERROR TypeError: Cannot read properties of undefined (reading 'getProfile')
ERROR TypeError: Cannot read properties of undefined (reading 'getProfile')
我正在尝试将本地 json 文件中的数据显示到 angular 12 的 table,但第一步我只想控制该文件中的数据。但是我发现了我在标题中写的错误。
这是我的代码:
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 {}
table-pagination-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[] = []
server-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
感谢您的关注,如果我的问题或我的英语有任何问题,请告诉我。这是我第一次 post 向 Whosebug 提问。
您必须删除 private serverHttp: ServerHttpService;
并改为添加以下代码。
constructor(private serverHttp: ServerHttpService) {}
您可以详细阅读 Angular 服务的依赖注入 here。
我正在尝试将本地 json 文件中的数据显示到 angular 12 的 table,但第一步我只想控制该文件中的数据。但是我发现了我在标题中写的错误。 这是我的代码: 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 {}
table-pagination-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[] = []
server-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
感谢您的关注,如果我的问题或我的英语有任何问题,请告诉我。这是我第一次 post 向 Whosebug 提问。
您必须删除 private serverHttp: ServerHttpService;
并改为添加以下代码。
constructor(private serverHttp: ServerHttpService) {}
您可以详细阅读 Angular 服务的依赖注入 here。