Угловой GET возвращает объект вместо массива

#angular #typescript #rest #get #jsobject

Вопрос:

При использовании API REST с Angular мой запрос GET возвращает объект. Я хочу иметь массив, чтобы я мог разрезать и отобразить содержимое с привязкой свойств.

Я чувствую, что решение включает функцию «карта», но предыдущие попытки привели к паре ключ:значение для каждой буквы каждого поля (!).

Я попробовал KeyValuePipe в HTML, но ничего не вижу, не знаю, где я ошибся.

Возможно ли, что my .ts не возвращает никакого значения??

Мой код компонента.ts:

   fetchForceDetail(){
    this.http
    .get<ForceDetail[]>('https://data.police.uk/api/forces/'   bedfordshire)
    .subscribe(forcedetails => {
      console.log(forcedetails);
      return forcedetails;
  });}
 

мой html:

 <div class="col-xs-12" *ngFor="let item of forcedetails | keyvalue">
  {{item.key}}:{{item.value}}
</div>
 

возвращенный объект:

 {
  "description": "<p>Bedfordshire Police is dedicated to protecting people and fighting crime together.</p>nn<p>At 477 square miles and with 664,500 people Bedfordshire is one of England’s smallest, yet most diverse, counties and faces complex crime challenges more usually seen in large metropolitan cities.</p>nn<p>More than half of its residents live in its largest towns, Luton and Bedford, which have diverse and often transient communities, alongside smaller market towns and rural parishes.</p>nn<p>Bedfordshire is a hub of transport link with London Luton Airport, the UK’s fifth busiest, the M1 and A1(M)motorways which traverse the county, and two principle railway lines that connect people with the heart of London in less than an hour.</p>nn<p>Bedfordshire has a complex mix of volume crime, serious crimes, drugs, gangs and terrorism threats.Every day our officers meet threats, harm and risks like those in large cities.</p>nn<p>Despite our relatively small size, we lead joint protective services which include Armed Policing, Dogs, Roads Policing and the Major Crime, for Bedfordshire, Cambridgeshire and Hertfordshire and are the lead force for the Eastern Region Special Operations Unit – a co - ordinated approach from seven forces in the region to tackle serious and organised crime and terrorism.</p>",
  "url": "http://www.bedfordshire.police.uk",
  "engagement_methods": [
    {
      "url": "https://www.bedfordshire.police.uk/",
      "type": null,
      "description": "<p>Latest news, information about crime, crime reduction advice and information about your area can be found on our website.<br />We offer a range of online services for reporting crime and suspicious activity, requesting information, giving feedback and applying for jobs.See our website for details of all our online services.</p>",
      "title": "Bedfordshire Police"
    },
    {
      "url": "http://www.facebook.com/bedspolice",
      "type": null,
      "description": "<p>Bedfordshire Police on Facebook</p>",
      "title": "Bedfordshire Police on Facebook"
    },
    {
      "url": "http://twitter.com/bedspolice",
      "type": null,
      "description": "<p>Bedfordshire Police on Twitter</p>",
      "title": "Bedfordshire Police on Twitter"
    },
    {
      "url": "http://www.youtube.com/bedfordshirepolice",
      "type": null,
      "description": "<p>Bedfordshire Police on YouTube</p>",
      "title": "Bedfordshire Police on YouTube"
    }
  ],
  "telephone": "101",
  "id": "bedfordshire",
  "name": "Bedfordshire Police"
}
 

Комментарии:

1. Это проблема с api. Ваш тип сообщает компилятору TS только то, что вы здесь ожидаете. Вы должны убедиться, что api возвращает правильный тип.

2. вы можете отобразить содержимое объекта с помощью: angular.io/api/common/KeyValuePipe

3. какова форма объекта?

Ответ №1:

Чтобы избежать оператора карты, вам следует использовать Lodash:

 const array = _.values(obj);
 

Вы можете ознакомиться с документацией здесь https://lodash.com/docs/4.17.15#values

Ответ №2:

Этот код возвращает массив значений, но в нем отсутствуют ключи.

   fetchForceDetail(){
    return this.http
    .get<ForceDetail[]>('https://data.police.uk/api/forces/'   this.force.id)
    .pipe(map(responseData => {
      const detailArray = [];
      for (const key in responseData) {
      if (responseData.hasOwnProperty(key))
        detailArray.push(responseData[key])
      }
      return detailArray;
    }))
    .subscribe(forcedetails => {
      console.log(forcedetails);
  });
}
 

Возвращенный массив:

 [
    "<p>Bedfordshire Police is dedicated to protecting people and fighting crime together.</p>nn<p>At 477 square miles and with 664,500 people Bedfordshire is one of England’s smallest, yet most diverse, counties and faces complex crime challenges more usually seen in large metropolitan cities.</p>nn<p>More than half of its residents live in its largest towns, Luton and Bedford, which have diverse and often transient communities, alongside smaller market towns and rural parishes.</p>nn<p>Bedfordshire is a hub of transport link with London Luton Airport, the UK’s fifth busiest, the M1 and A1(M)motorways which traverse the county, and two principle railway lines that connect people with the heart of London in less than an hour.</p>nn<p>Bedfordshire has a complex mix of volume crime, serious crimes, drugs, gangs and terrorism threats.Every day our officers meet threats, harm and risks like those in large cities.</p>nn<p>Despite our relatively small size, we lead joint protective services which include Armed Policing, Dogs, Roads Policing and the Major Crime, for Bedfordshire, Cambridgeshire and Hertfordshire and are the lead force for the Eastern Region Special Operations Unit – a co - ordinated approach from seven forces in the region to tackle serious and organised crime and terrorism.</p>",
    "http://www.bedfordshire.police.uk",
    [
        {
            "url": "https://www.bedfordshire.police.uk/",
            "type": null,
            "description": "<p>Latest news, information about crime, crime reduction advice and information about your area can be found on our website.<br />We offer a range of online services for reporting crime and suspicious activity, requesting information, giving feedback and applying for jobs.See our website for details of all our online services.</p>",
            "title": "Bedfordshire Police"
        },
        {
            "url": "http://www.facebook.com/bedspolice",
            "type": null,
            "description": "<p>Bedfordshire Police on Facebook</p>",
            "title": "Bedfordshire Police on Facebook"
        },
        {
            "url": "http://twitter.com/bedspolice",
            "type": null,
            "description": "<p>Bedfordshire Police on Twitter</p>",
            "title": "Bedfordshire Police on Twitter"
        },
        {
            "url": "http://www.youtube.com/bedfordshirepolice",
            "type": null,
            "description": "<p>Bedfordshire Police on YouTube</p>",
            "title": "Bedfordshire Police on YouTube"
        }
    ],
    "101",
    "bedfordshire",
    "Bedfordshire Police"
]