【问题标题】:Send Map from SpringBoot backend to Angular View and save it in LocalStorage将 Map 从 SpringBoot 后端发送到 Angular View 并将其保存在 LocalStorage
【发布时间】:2021-04-18 10:51:18
【问题描述】:

我被困在任务上。我需要将 Map 从 Spring Boot 后端发送到 Angular 应用程序。

控制器

@GetMapping("/dict")
    public Map<String, String> getAll(){
        return dictionaryService.getAll();
}
@Entity
public class Entity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "key")
    private String key;
    @Column(name = "value")
    private String value;
public class Model {

    private Map<String, String> dict;

    public Map<String, String> getDict() {
        return dict;
    }

    public Model setDict(Map<String, String> dict) {
        this.dict = dict;
        return this;
    }
}

服务

public Map<String, String> getAll() {
       
        var model = new DictionaryModel()
                .setDictionary(StreamSupport.stream(dictionaryRepository.findAll().spliterator(), false)
                .collect(Collectors.toMap(DictionaryEntity::getKey, DictionaryEntity::getValue)));

        return model.getDictionary();
    }

在邮递员中我有:

{
    "key": "Some Value",
    "other-key": "Other Value",
}

我与 Angular 几乎没有共同之处,但我需要这样做。从后端下载的地图必须保存在localStorage中,然后从视图中显示的key和value取的localstorage下载。我不知道该怎么做。我的解决方案,即使在这里我也不坚持,但没有奏效。正如我所说,我对 Angular 了解不多。我请求你的理解。有人可以帮帮我吗?显示解决方案或示例解决方案的方法。

您好!

【问题讨论】:

  • 您需要从控制器发送地图,对吗?尝试在 responseEntity 中发送它
  • 对,但不一定是模型对象。更多的是关于如何在 Angular 中映射类和服务以正确读取它

标签: java angular typescript spring-boot local-storage


【解决方案1】:

您在 Angular 中的服务可能是:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class YourService {
  constructor(
      private readonly _http: HttpClient) {
  }
  getDictMap(): Observable<{
    'key',
    'other-key',
  }> {
    return this._http.get<any>('/dict').pipe(
      map(res => res)
    );
  }
}

并且在您的组件中,您可以将其存储在 localStorage 中:

import {Component, OnInit, OnDestroy} from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
})
export class YourComponent implements OnInit, OnDestroy {
  private sub: Subscription;
  public dict: {key, value}[];

  constructor(private yourService: YourService) {}

  ngOnInit() {
    this.sub = this.yourService.getDict().subscribe({
      next: res => {
        this.dict = Object.entries(res).map(([k, v]) => {
          return {key: k, value: v};
        });
        localStorage.setItem('dict', JSON.stringify(this.dict));
      },
      error: err => {
        console.error('An error! ', err);
      }
    });
  }

  ngOnDestroy() {
    if (this.sub) {
      this.sub.unsubscribe();
    }
  }
}

在 Angular 视图 html 中:

<div *ngIf="dict">
  <div *ngFor="let elem of dict" class="card">
    {{elem.key}}: {{elem.value}}
  </div>
</div>

如果你不知道你的 dict 对象的键,你可以在输出 Observable 中插入:

getDictMap(): Observable<object> {

【讨论】:

  • 非常感谢您的回答! getDictMap(): Observable
  • getDictMap(): Observable 这个“对象”意味着我需要创建类并声明 e.q: dict: Map ?
  • 不,对象是通用对象。如果您知道密钥,您还可以在 Angular 中创建模型。
  • 如果您有很多未知键,请使用 Observable。它是一个泛型类型,就像在 Java 中一样。
  • 好的,我知道了。但现在什么是“this.sub”?我现在如何在 html 视图中显示它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多