将数据与订阅一起保存在角度8中

问题描述 投票:0回答:2

您好,我在将数据保存到角度为8的订阅中时遇到问题。

当我制作此this.service.getAll().subscribe(response => console.log(this.itemList = response))

并且打印itemList数组为空,我尝试在订阅中打印响应,并且响应中有数据。

我试图以这种方式在订阅和本地数组的打印中进行打印:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ItemService } from 'src/service/item.service';
import { Item } from 'src/DTO/item';

@Component({
  selector: 'app-crafting-dashboard',
  templateUrl: './crafting-dashboard.component.html',
  styleUrls: ['./crafting-dashboard.component.css']
})
export class CraftingDashboardComponent implements OnInit{
  itemList: Item[] = [];

  constructor(private router: Router, protected service: ItemService) {
  }

  ngOnInit() {
    this.service.getAll().subscribe(response => console.log("Reponse:" + response));
    console.log("Constrol print" + this.itemList);
  }

  getAll(){

  }

}

我注意到,首先在控制台中出现console.log(“ Constrol print” + this.itemList);并在打印订阅之后。可能是这个问题吗?!?!??

这是我的服务(我提供了抽象服务,并在特定服务中为实体添加了特定方法:

import { Service } from './service';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

export class AbstractService<DTO> implements Service<DTO> {
    type: string = '';
    port: string = '8080';

    constructor(protected http: HttpClient){}

    getAll(): Observable<DTO[]> {
        return this.http.get<DTO[]>('http://localhost:' + this.port + '/' + this.type + '/getAll');
    }

    read(id: number): Observable<DTO> {
        return this.http.get<DTO>('http://localhost:' + this.port + '/' + this.type + '/read?id=' + id);
    }

    insert(dto: DTO): Observable<DTO> {
        return this.http.post<DTO>('http://localhost:' + this.port + '/' + this.type + '/insert', dto);
    }

    update(dto: DTO): Observable<DTO> {
        return this.http.put<DTO>('http://localhost:' + this.port + '/' + this.type + '/update', dto);
    }

    delete(id: number): Observable<any> {
        return this.http.delete('http://localhost:' + this.port + '/' + this.type + '/delete?id=' + id);
    }


}

后端是用java用spring编写的

javascript angular observable angular8 observer-pattern
2个回答
0
投票

使用此代码:

ngOnInit() {
    this.service.getAll().subscribe(response => console.log("Reponse:" + response));
    console.log("Constrol print" + this.itemList);
}

回调response => console.log("Reponse:" + response)被延迟,它在收到HTTP响应时执行。这解释了您观察到的行为(“响应:”之前显示“ Constrol打印”)。

如果您必须对接收到的数据进行处理,请在回调中进行,而不要在ngOnInit中进行:

this.service.getAll().subscribe(response => {
    console.log("Reponse:" + response);
    //Whatever you want to do with the response and the variables assigned to the response goes here
});

0
投票

喜欢这样

this.service.getAll().subscribe(response => {
    this.itemList=response;
    console.log("Console print" + this.itemList);
});

© www.soinside.com 2019 - 2024. All rights reserved.