когда я пытаюсь нажать свой массив, у меня возникает следующая ошибка:
Cannot read property 'push' of null
Я попытался решить свою проблему, инициализировав массив, но это не работает. Извините, я новичок в программировании и не понимаю, почему это не работает. Спасибо за помощь.
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)





Попробуй это:
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));
}
EDIT:
В сервисе:
balades: Balade[] = [];
Я тоже пробовал, но у меня та же проблема. У меня сейчас нет Stackblitz (позже попробую), но вот мой Githubhttps://github.com/Joan68/Motard-Alsace
@PrashantPimpale Извините, я думаю, что мой git не совсем актуален. экспортный класс BaladeService { baseUrl = './htdocs/api'; баллады: Балада[] = []; Это фигурирует в моей текущей версии
@PrashantPimpale Да, я могу, вы используете Discord?
Вы не использовали функцию стрелки для определения своего метода store, поэтому this относится к функции, а не к классу.
getBalades = (): void => {
this.baladeService.getAll().subscribe(
(res: Balade[]) => {
this.balades = res;
},
(err) => {
this.error = err;
}
);
}
Да, я думаю, что сделал
Можете ли вы отредактировать свой пост, чтобы показать текущее состояние службы?
Что-то не так с balades, который не работает как массив, потому что свойство массива push не работает.
Вы можете сделать его массивом, назначив пустой массив.
Например
this.arrayName = this.arrayName || []; //assign an empty array
В balade.service.ts
store(balade: Balade): Observable<Balade[]> {
return this.http.post(`${this.baseUrl}/store.php`, { data: balade })
.pipe(map((res) => {
this.balades = this.balades || [];
this.balades.push(res['data']);
return this.balades;
}),
catchError(this.handleError));
}
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.info(notesObj);
showNotes();
});
пожалуйста, и этот "push of null"
Пожалуйста, не публикуйте только код в качестве ответа, но также объясните, что делает ваш код и как он решает проблему вопроса. Ответы с объяснением, как правило, более полезны и качественны, и с большей вероятностью привлекут положительные голоса.
Вы можете отредактировать свой ответ и добавить объяснение к своему ответу.
Я думаю, что стрелочная функция предпочтительнее алиасинга
this.