当我尝试推送数组时,出现以下错误:
无法读取null的属性“ push”
我试图通过初始化数组来解决我的问题,但是它不起作用。抱歉,我是新手,我不明白为什么它不起作用。 谢谢您的帮助。
balade.ts:
export class Balade {
NOM_BALADE: string;
DATE_DEPART: string;
LIEU_RDV: string;
ID_BALADE?: number;
constructor(NOM_BALADE: string, DATE_DEPART: string, LIEU_RDV: string, ID_BALADE?: number) {
this.NOM_BALADE = NOM_BALADE;
this.DATE_DEPART = DATE_DEPART;
this.LIEU_RDV = LIEU_RDV;
this.ID_BALADE = ID_BALADE;
}
}
balade.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Balade } from './balade';
@Injectable({
providedIn: 'root'
})
export class BaladeService {
baseUrl = './htdocs/api';
balades: Balade[] = [];
constructor(private http: HttpClient) { }
getAll(): Observable<Balade[]> {
return this.http.get(`${this.baseUrl}/list.php`).pipe(
map((res) => {
this.balades = res['data'];
return this.balades;
}),
catchError(this.handleError));
}
store(balade: Balade): Observable<Balade[]> {
return this.http.post(`${this.baseUrl}/store.php`, { data: balade })
.pipe(map((res) => {
this.balades.push(res['data']);
return this.balades;
}),
catchError(this.handleError));
}
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { Balade } from './balade';
import { BaladeService } from './balade.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
balades: Balade[] = [];
error = '';
success = '';
balade = new Balade('', '','');
constructor(private baladeService: BaladeService) {
}
ngOnInit() {
this.getBalades();
}
getBalades(): void {
this.baladeService.getAll().subscribe(
(res: Balade[]) => {
this.balades = res;
},
(err) => {
this.error = err;
}
);
}
addBalade(f) {
this.resetErrors();
this.baladeService.store(this.balade)
.subscribe(
(res: Balade[]) => {
// Update the list of balades
this.balades = res;
// Inform the user
this.success = 'Created successfully';
// Reset the form
f.reset();
},
(err) => this.error = err
);
}
这是错误:
TypeError: Cannot read property 'push' of null
at t.project (main.6f2a73c37c9b189cf02f.js:1)
at t._next (main.6f2a73c37c9b189cf02f.js:1)
at t.next (main.6f2a73c37c9b189cf02f.js:1)
at t._next (main.6f2a73c37c9b189cf02f.js:1)
at t.next (main.6f2a73c37c9b189cf02f.js:1)
at t._next (main.6f2a73c37c9b189cf02f.js:1)
at t.next (main.6f2a73c37c9b189cf02f.js:1)
at t.notifyNext (main.6f2a73c37c9b189cf02f.js:1)
at t._next (main.6f2a73c37c9b189cf02f.js:1)
at t.next (main.6f2a73c37c9b189cf02f.js:1)
答案 0 :(得分:0)
尝试一下:
store(balade: Balade): Observable<Balade[]> {
var ref = this; // Store the this into one variable and then use that variable to access a global scope
return this.http.post(`${this.baseUrl}/store.php`, { data: balade })
.pipe(map((res) => {
ref.balades.push(res['data']);
return this.balades;
}),
catchError(this.handleError));
}
编辑:
在使用中:
balades: Balade[] = [];
答案 1 :(得分:0)
您没有使用箭头函数来定义store
方法,因此this
的作用域是该函数,而不是类。
getBalades = (): void => {
this.baladeService.getAll().subscribe(
(res: Balade[]) => {
this.balades = res;
},
(err) => {
this.error = err;
}
);
}
答案 2 :(得分:0)
更改此
store(balade: Balade): Observable<Balade[]> {
return this.http.post(`${this.baseUrl}/store.php`, { data: balade })
.pipe(map((res) => {
this.balades.push(res['data']);
return this.balades;
}),
catchError(this.handleError));
}
到
store(balade: Balade): Observable<Balade[]> {
return this.http.post(`${this.baseUrl}/store.php`, { data: balade })
.pipe(map((res) => {
this.balades = this.balades || []; //this will make your array empty if null
this.balades.push(res['data']);
return this.balades;
}),
catchError(this.handleError));
}
this.balades在商店运行时为空。或者您可以尝试
constructor(private http: HttpClient) { }
到
constructor(private http: HttpClient) { getAll(); } // fill this.balades
答案 3 :(得分:0)
def read_data():
# reading from file
file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/PlanePos.txt", "r")
planepos = file.readline()
file.close()
file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/AirportPosition.txt", "r")
airportpos = file.readline()
file.close()
# ==================================================================
# spliting and getting numbers
#plane_X, plane_Y, plane_Z = map(float, planepos.strip('() \n').split(','))
#airport_X, airport_Y, airport_Z = map(float, airportpos.strip('() \n').split(','))
planepos=planepos.strip('() \n').split(',')
airportpos=airportpos.strip('() \n').split(',')
return planepos[0], planepos[1], planepos[2], airportpos[0], airportpos[1], airportpos[2]
出了点问题,由于数组的push属性不起作用,它不能作为数组工作。
您可以通过分配一个空数组来使其成为数组。
例如
balades
在balade.service.ts
this.arrayName = this.arrayName || []; //assign an empty array
答案 4 :(得分:0)
let create = document.getElementById("create");
create.addEventListener("click", function(e) {
let addTxt = document.getElementById("addTxt");
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value);
localStorage.setItem("notes", JSON.stringify(notesObj));
addTxt.value = "";
// console.log(notesObj);
showNotes();
});