问:
API call not being made as it is not reflecting in the network tab in Google chrome developer tools
I am trying to make a call to a recipe API, parse the response and then show it in the HTML. Here is the code:

display-recipes.component.html

```<code><p>display-recipes works!</p>
<div id='display_recipe'  *ngFor="let recipe of recipeResult.hits">
    {{calories}}  {{recipe}}
</div>
</code>```

display-recipes.component.ts

```<code>import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

@Component({
  selector: 'app-display-recipes',
  templateUrl: './display-recipes.component.html',
  styleUrls: ['./display-recipes.component.css']
})
export class DisplayRecipesComponent implements OnInit {

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
    this.recipeResult = new RecipeGlobal();
    this.getRecipeInfo();

  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}
</code>```

search-recipe.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { RecipeGlobal, Recipe } from './pojos/RecipeGlobal';
import { Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators'
import { Component, OnInit, Input } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SearchRecipeService {

  constructor(
    private http: HttpClient) {}

    private searchUrl = 'https://api.edamam.com/search?q=bandejapaisa&app_id=xxxx&app_key=xxxxxxx&from=0&to=3&calories=591-722&health=alcohol-free';

  getRecipeInfo(): Observable<RecipeGlobal>{
         return this.http.get<RecipeGlobal>(this.searchUrl)
         .pipe(

           catchError(_ => {console.log("error"); return [];})
         );
  }

}
</code>```

RecipeGlobal.ts -> mapping mojo for the API response

```<code>export class RecipeGlobal{
    q!: String;
    hits!: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}
</code>```

The response from the API call should be this:

{

```<code>  "q": "bandeja paisa",
  "from": 0,
  "to": 3,
  "more": false,
  "count": 1,
  "hits": [
    {
      "recipe": {
        "uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_023ae14ca70ba202bfa5dddfd60564a8",
        "label": "Bandeja Paisa",
        "image": "https://www.edamam.com/web-img/e7e/e7e5236b4b1c067c881c25004ee9e239.jpg",
        "source": "My Recipes",
        "url": "http://www.myrecipes.com/recipe/bandeja-paisa",
        "shareAs": "http://www.edamam.com/recipe/bandeja-paisa-023ae14ca70ba202bfa5dddfd60564a8/bandeja+paisa/alcohol-free/591-722-cal",
        "yield": 4.0,
        "dietLabels": [
          "Low-Carb"
        ],
        "healthLabels": [
          "Sugar-Conscious",
          "Peanut-Free",
          "Tree-Nut-Free",
          "Alcohol-Free"
        ],
        "cautions": [],
        "ingredientLines": [
          "1 pound skinless pork belly",
          "2 teaspoons kosher salt",
          "2 teaspoons granulated sugar",
          "1/2 teaspoon ground cumin"
        ],
        "ingredients": [
          {
            "text": "1 pound skinless pork belly",
            "weight": 453.59237
          },
          {
            "text": "2 teaspoons kosher salt",
            "weight": 9.70833333382575
          },
          {
            "text": "2 teaspoons granulated sugar",
            "weight": 8.4
          },
          {
            "text": "1/2 teaspoon ground cumin",
            "weight": 1.05
          }
        ],
        "calories": 2386.0539766,
        "totalWeight": 465.4413539831457,
        "totalTime": 780.0,
        "totalNutrients": {
          "ENERC_KCAL": {
            "label": "Energy",
            "quantity": 2386.0539766,
            "unit": "kcal"
          },
          "FAT": {
            "label": "Fat",
            "quantity": 240.68315033700003,
            "unit": "g"
          },
          "FASAT": {
            "label": "Saturated",
            "quantity": 87.695522621,
            "unit": "g"
          },
          "FAMS": {
            "label": "Monounsaturated",
            "quantity": 112.18473539000001,
            "unit": "g"
          },
          "FAPU": {
            "label": "Polyunsaturated",
            "quantity": 25.662398405000005,
            "unit": "g"
          },
          "CHOCDF": {
            "label": "Carbs",
            "quantity": 8.86284,
            "unit": "g"
          },
          "FIBTG": {
            "label": "Fiber",
            "quantity": 0.11025,
            "unit": "g"
          },
          "SUGAR": {
            "label": "Sugars",
            "quantity": 8.406825,
            "unit": "g"
          },
          "SUGAR.added": {
            "label": "Sugars, added",
            "quantity": 8.3832,
            "unit": "g"
          },
          "PROCNT": {
            "label": "Protein",
            "quantity": 42.552532358,
            "unit": "g"
          },
          "CHOLE": {
            "label": "Cholesterol",
            "quantity": 326.5865064,
            "unit": "mg"
          },
          "NA": {
            "label": "Sodium",
            "quantity": 1076.7957705876,
            "unit": "mg"
          },
          "CA": {
            "label": "Calcium",
            "quantity": 33.114874655954964,
            "unit": "mg"
          },
          "MG": {
            "label": "Magnesium",
            "quantity": 22.01068463983146,
            "unit": "mg"
          },
          "K": {
            "label": "Potassium",
            "quantity": 858.2798032186518,
            "unit": "mg"
          },
          "FE": {
            "label": "Iron",
            "quantity": 3.0675769711443808,
            "unit": "mg"
          },
          "ZN": {
            "label": "Zinc",
            "quantity": 4.6802811579831465,
            "unit": "mg"
          },
          "P": {
            "label": "Phosphorus",
            "quantity": 495.1192596000001,
            "unit": "mg"
          },
          "VITA_RAE": {
            "label": "Vitamin A",
            "quantity": 14.279771100000001,
            "unit": "µg"
          },
          "VITC": {
            "label": "Vitamin C",
            "quantity": 1.4416271100000002,
            "unit": "mg"
          },
          "THIA": {
            "label": "Thiamin (B1)",
            "quantity": 1.8028197852000003,
            "unit": "mg"
          },
          "RIBF": {
            "label": "Riboflavin (B2)",
            "quantity": 1.1027230354000002,
            "unit": "mg"
          },
          "NIA": {
            "label": "Niacin (B3)",
            "quantity": 21.126516933900003,
            "unit": "mg"
          },
          "VITB6A": {
            "label": "Vitamin B6",
            "quantity": 0.594237581,
            "unit": "mg"
          },
          "FOLDFE": {
            "label": "Folate equivalent (total)",
            "quantity": 4.640923700000001,
            "unit": "µg"
          },
          "FOLFD": {
            "label": "Folate (food)",
            "quantity": 4.640923700000001,
            "unit": "µg"
          },
          "VITB12": {
            "label": "Vitamin B12",
            "quantity": 3.810175908,
            "unit": "µg"
          },
          "TOCPHA": {
            "label": "Vitamin E",
            "quantity": 1.8039752430000002,
            "unit": "mg"
          },
          "VITK1": {
            "label": "Vitamin K",
            "quantity": 0.05670000000000001,
            "unit": "µg"
          },
          "WATER": {
            "label": "Water",
            "quantity": 166.7409447059663,
            "unit": "g"
          }
        },
        "totalDaily": {
          "ENERC_KCAL": {
            "label": "Energy",
            "quantity": 119.30269883000001,
            "unit": "%"
          },
          "FAT": {
            "label": "Fat",
            "quantity": 370.2817697492308,
            "unit": "%"
          },
          "FASAT": {
            "label": "Saturated",
            "quantity": 438.477613105,
            "unit": "%"
          },
          "CHOCDF": {
            "label": "Carbs",
            "quantity": 2.95428,
            "unit": "%"
          },
          "FIBTG": {
            "label": "Fiber",
            "quantity": 0.441,
            "unit": "%"
          },
          "PROCNT": {
            "label": "Protein",
            "quantity": 85.105064716,
            "unit": "%"
          },
          "CHOLE": {
            "label": "Cholesterol",
            "quantity": 108.8621688,
            "unit": "%"
          },
          "NA": {
            "label": "Sodium",
            "quantity": 44.86649044115,
            "unit": "%"
          },
          "CA": {
            "label": "Calcium",
            "quantity": 3.3114874655954964,
            "unit": "%"
          },
          "MG": {
            "label": "Magnesium",
            "quantity": 5.240639199959872,
            "unit": "%"
          },
          "K": {
            "label": "Potassium",
            "quantity": 18.261272408907484,
            "unit": "%"
          },
          "FE": {
            "label": "Iron",
            "quantity": 17.042094284135448,
            "unit": "%"
          },
          "ZN": {
            "label": "Zinc",
            "quantity": 42.548010527119516,
            "unit": "%"
          },
          "P": {
            "label": "Phosphorus",
            "quantity": 70.73132280000002,
            "unit": "%"
          },
          "VITA_RAE": {
            "label": "Vitamin A",
            "quantity": 1.5866412333333333,
            "unit": "%"
          },
          "VITC": {
            "label": "Vitamin C",
            "quantity": 1.6018079000000003,
            "unit": "%"
          },
          "THIA": {
            "label": "Thiamin (B1)",
            "quantity": 150.23498210000002,
            "unit": "%"
          },
          "RIBF": {
            "label": "Riboflavin (B2)",
            "quantity": 84.82484887692308,
            "unit": "%"
          },
          "NIA": {
            "label": "Niacin (B3)",
            "quantity": 132.040730836875,
            "unit": "%"
          },
          "VITB6A": {
            "label": "Vitamin B6",
            "quantity": 45.71058315384615,
            "unit": "%"
          },
          "FOLDFE": {
            "label": "Folate equivalent (total)",
            "quantity": 1.1602309250000002,
            "unit": "%"
          },
          "VITB12": {
            "label": "Vitamin B12",
            "quantity": 158.7573295,
            "unit": "%"
          },
          "TOCPHA": {
            "label": "Vitamin E",
            "quantity": 12.026501620000001,
            "unit": "%"
          },
          "VITK1": {
            "label": "Vitamin K",
            "quantity": 0.04725000000000001,
            "unit": "%"
          }
        },
        "digest": [
          {
            "label": "Fat",
            "tag": "FAT",
            "schemaOrgTag": "fatContent",
            "total": 240.68315033700003,
            "hasRDI": true,
            "daily": 370.2817697492308,
            "unit": "g",
            "sub": [
              {
                "label": "Saturated",
                "tag": "FASAT",
                "schemaOrgTag": "saturatedFatContent",
                "total": 87.695522621,
                "hasRDI": true,
                "daily": 438.477613105,
                "unit": "g"
              },
              {
                "label": "Trans",
                "tag": "FATRN",
                "schemaOrgTag": "transFatContent",
                "total": 0.0,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Monounsaturated",
                "tag": "FAMS",
                "schemaOrgTag": null,
                "total": 112.18473539000001,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Polyunsaturated",
                "tag": "FAPU",
                "schemaOrgTag": null,
                "total": 25.662398405000005,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              }
            ]
          },
          {
            "label": "Carbs",
            "tag": "CHOCDF",
            "schemaOrgTag": "carbohydrateContent",
            "total": 8.86284,
            "hasRDI": true,
            "daily": 2.95428,
            "unit": "g",
            "sub": [
              {
                "label": "Carbs (net)",
                "tag": "CHOCDF.net",
                "schemaOrgTag": null,
                "total": 8.75259,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Fiber",
                "tag": "FIBTG",
                "schemaOrgTag": "fiberContent",
                "total": 0.11025,
                "hasRDI": true,
                "daily": 0.441,
                "unit": "g"
              },
              {
                "label": "Sugars",
                "tag": "SUGAR",
                "schemaOrgTag": "sugarContent",
                "total": 8.406825,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Sugars, added",
                "tag": "SUGAR.added",
                "schemaOrgTag": null,
                "total": 8.3832,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              }
            ]
          },
          {
            "label": "Protein",
            "tag": "PROCNT",
            "schemaOrgTag": "proteinContent",
            "total": 42.552532358,
            "hasRDI": true,
            "daily": 85.105064716,
            "unit": "g"
          },
          {
            "label": "Cholesterol",
            "tag": "CHOLE",
            "schemaOrgTag": "cholesterolContent",
            "total": 326.5865064,
            "hasRDI": true,
            "daily": 108.8621688,
            "unit": "mg"
          },
          {
            "label": "Sodium",
            "tag": "NA",
            "schemaOrgTag": "sodiumContent",
            "total": 1076.7957705876,
            "hasRDI": true,
            "daily": 44.86649044115,
            "unit": "mg"
          },
          {
            "label": "Calcium",
            "tag": "CA",
            "schemaOrgTag": null,
            "total": 33.114874655954964,
            "hasRDI": true,
            "daily": 3.3114874655954964,
            "unit": "mg"
          },
          {
            "label": "Magnesium",
            "tag": "MG",
            "schemaOrgTag": null,
            "total": 22.01068463983146,
            "hasRDI": true,
            "daily": 5.240639199959872,
            "unit": "mg"
          },
          {
            "label": "Potassium",
            "tag": "K",
            "schemaOrgTag": null,
            "total": 858.2798032186518,
            "hasRDI": true,
            "daily": 18.261272408907484,
            "unit": "mg"
          },
          {
            "label": "Iron",
            "tag": "FE",
            "schemaOrgTag": null,
            "total": 3.0675769711443808,
            "hasRDI": true,
            "daily": 17.042094284135448,
            "unit": "mg"
          },
          {
            "label": "Zinc",
            "tag": "ZN",
            "schemaOrgTag": null,
            "total": 4.6802811579831465,
            "hasRDI": true,
            "daily": 42.548010527119516,
            "unit": "mg"
          },
          {
            "label": "Phosphorus",
            "tag": "P",
            "schemaOrgTag": null,
            "total": 495.1192596000001,
            "hasRDI": true,
            "daily": 70.73132280000002,
            "unit": "mg"
          },
          {
            "label": "Vitamin A",
            "tag": "VITA_RAE",
            "schemaOrgTag": null,
            "total": 14.279771100000001,
            "hasRDI": true,
            "daily": 1.5866412333333333,
            "unit": "µg"
          },
          {
            "label": "Vitamin C",
            "tag": "VITC",
            "schemaOrgTag": null,
            "total": 1.4416271100000002,
            "hasRDI": true,
            "daily": 1.6018079000000003,
            "unit": "mg"
          },
          {
            "label": "Thiamin (B1)",
            "tag": "THIA",
            "schemaOrgTag": null,
            "total": 1.8028197852000003,
            "hasRDI": true,
            "daily": 150.23498210000002,
            "unit": "mg"
          },
          {
            "label": "Riboflavin (B2)",
            "tag": "RIBF",
            "schemaOrgTag": null,
            "total": 1.1027230354000002,
            "hasRDI": true,
            "daily": 84.82484887692308,
            "unit": "mg"
          },
          {
            "label": "Niacin (B3)",
            "tag": "NIA",
            "schemaOrgTag": null,
            "total": 21.126516933900003,
            "hasRDI": true,
            "daily": 132.040730836875,
            "unit": "mg"
          },
          {
            "label": "Vitamin B6",
            "tag": "VITB6A",
            "schemaOrgTag": null,
            "total": 0.594237581,
            "hasRDI": true,
            "daily": 45.71058315384615,
            "unit": "mg"
          },
          {
            "label": "Folate equivalent (total)",
            "tag": "FOLDFE",
            "schemaOrgTag": null,
            "total": 4.640923700000001,
            "hasRDI": true,
            "daily": 1.1602309250000002,
            "unit": "µg"
          },
          {
            "label": "Folate (food)",
            "tag": "FOLFD",
            "schemaOrgTag": null,
            "total": 4.640923700000001,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "µg"
          },
          {
            "label": "Folic acid",
            "tag": "FOLAC",
            "schemaOrgTag": null,
            "total": 0.0,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "µg"
          },
          {
            "label": "Vitamin B12",
            "tag": "VITB12",
            "schemaOrgTag": null,
            "total": 3.810175908,
            "hasRDI": true,
            "daily": 158.7573295,
            "unit": "µg"
          },
          {
            "label": "Vitamin D",
            "tag": "VITD",
            "schemaOrgTag": null,
            "total": 0.0,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "µg"
          },
          {
            "label": "Vitamin E",
            "tag": "TOCPHA",
            "schemaOrgTag": null,
            "total": 1.8039752430000002,
            "hasRDI": true,
            "daily": 12.026501620000001,
            "unit": "mg"
          },
          {
            "label": "Vitamin K",
            "tag": "VITK1",
            "schemaOrgTag": null,
            "total": 0.05670000000000001,
            "hasRDI": true,
            "daily": 0.04725000000000001,
            "unit": "µg"
          },
          {
            "label": "Sugar alcohols",
            "tag": "Sugar.alcohol",
            "schemaOrgTag": null,
            "total": 0.0,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "g"
          },
          {
            "label": "Water",
            "tag": "WATER",
            "schemaOrgTag": null,
            "total": 166.7409447059663,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "g"
          }
        ]
      },
      "bookmarked": false,
      "bought": false
    }
  ]
}
</code>```

I am just parsing a few elements in the response by using the mentioned POJO class above. I am seeing the component is loading properly from the parent component but it's not displaying data inside the div as the API call is not being made. I am seeing the error log displayed in the console but the API call is not showing up in the network tab.

答:
You have some misunderstandings regarding the classes in typescript. Classes in the typescript are not some magic. You have only defined the class and expect the angular to automatically map the raw response to the actual class structure. They don't. You have to manually map the raw response to the actual class defined structure.

  getRecipeInfo(): Observable<RecipeGlobal>{
         return this.http.get<RecipeGlobal>(this.searchUrl)
         .pipe(
           map(res => this.mapRawResponse(res))
           catchError(_ => {console.log("error"); return [];})
         );
  }

    private mapRawResponse(rawResponse): RecipeGlobal {
          //... your code to map the response to Recipe.
    }

```

<p>If you don't want to map the response, then change the structure of your class definition to match the raw response.  </p>

<p>As for the no API calls being shown in the Network tab, check the filters on it, you may using some filters (css/Img/Media/etc). Switch it to xhr/All to see.</p>

<p><strong>Updated with proper class</strong><br>
Use this class instead to get the type support:</p>

<pre class="lang-js prettyprint-override"><code>
export interface RecipeGlobal {
    q:     string;
    from:  number;
    to:    number;
    more:  boolean;
    count: number;
    hits:  Hit[];
}

export interface Hit {
    recipe:     Recipe;
    bookmarked: boolean;
    bought:     boolean;
}

export interface Recipe {
    uri:             string;
    label:           string;
    image:           string;
    source:          string;
    url:             string;
    shareAs:         string;
    yield:           number;
    dietLabels:      string[];
    healthLabels:    string[];
    cautions:        any[];
    ingredientLines: string[];
    ingredients:     Ingredient[];
    calories:        number;
    totalWeight:     number;
    totalTime:       number;
    totalNutrients:  { [key: string]: Total };
    totalDaily:      { [key: string]: Total };
    digest:          Digest[];
}

export interface Digest {
    label:        string;
    tag:          string;
    schemaOrgTag: null | string;
    total:        number;
    hasRDI:       boolean;
    daily:        number;
    unit:         Unit;
    sub?:         Digest[];
}

export enum Unit {
    Empty = "%",
    G = "g",
    Kcal = "kcal",
    Mg = "mg",
    Μg = "µg",
}

export interface Ingredient {
    text:   string;
    weight: number;
}

export interface Total {
    label:    string;
    quantity: number;
    unit:     Unit;
}

</code>```

Body:
I am trying to make a call to a recipe API, parse the response and then show it in the HTML. Here is the code:

display-recipes.component.html

display-recipes works!

    {{calories}}  {{recipe}}

display-recipes.component.ts

import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

@Component({
  selector: 'app-display-recipes',
  templateUrl: './display-recipes.component.html',
  styleUrls: ['./display-recipes.component.css']
})
export class DisplayRecipesComponent implements OnInit {

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
    this.recipeResult = new RecipeGlobal();
    this.getRecipeInfo();

  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}

search-recipe.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { RecipeGlobal, Recipe } from './pojos/RecipeGlobal';
import { Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators'
import { Component, OnInit, Input } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SearchRecipeService {

  constructor(
    private http: HttpClient) {}

    private searchUrl = 'https://api.edamam.com/search?q=bandejapaisa&app_id=xxxx&app_key=xxxxxxx&from=0&to=3&calories=591-722&health=alcohol-free';

  getRecipeInfo(): Observable<RecipeGlobal>{
         return this.http.get<RecipeGlobal>(this.searchUrl)
         .pipe(

           catchError(_ => {console.log("error"); return [];})
         );
  }

}

RecipeGlobal.ts -> mapping mojo for the API response

export class RecipeGlobal{
    q!: String;
    hits!: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}

The response from the API call should be this:

{

  "q": "bandeja paisa",
  "from": 0,
  "to": 3,
  "more": false,
  "count": 1,
  "hits": [
    {
      "recipe": {
        "uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_023ae14ca70ba202bfa5dddfd60564a8",
        "label": "Bandeja Paisa",
        "image": "https://www.edamam.com/web-img/e7e/e7e5236b4b1c067c881c25004ee9e239.jpg",
        "source": "My Recipes",
        "url": "http://www.myrecipes.com/recipe/bandeja-paisa",
        "shareAs": "http://www.edamam.com/recipe/bandeja-paisa-023ae14ca70ba202bfa5dddfd60564a8/bandeja+paisa/alcohol-free/591-722-cal",
        "yield": 4.0,
        "dietLabels": [
          "Low-Carb"
        ],
        "healthLabels": [
          "Sugar-Conscious",
          "Peanut-Free",
          "Tree-Nut-Free",
          "Alcohol-Free"
        ],
        "cautions": [],
        "ingredientLines": [
          "1 pound skinless pork belly",
          "2 teaspoons kosher salt",
          "2 teaspoons granulated sugar",
          "1/2 teaspoon ground cumin"
        ],
        "ingredients": [
          {
            "text": "1 pound skinless pork belly",
            "weight": 453.59237
          },
          {
            "text": "2 teaspoons kosher salt",
            "weight": 9.70833333382575
          },
          {
            "text": "2 teaspoons granulated sugar",
            "weight": 8.4
          },
          {
            "text": "1/2 teaspoon ground cumin",
            "weight": 1.05
          }
        ],
        "calories": 2386.0539766,
        "totalWeight": 465.4413539831457,
        "totalTime": 780.0,
        "totalNutrients": {
          "ENERC_KCAL": {
            "label": "Energy",
            "quantity": 2386.0539766,
            "unit": "kcal"
          },
          "FAT": {
            "label": "Fat",
            "quantity": 240.68315033700003,
            "unit": "g"
          },
          "FASAT": {
            "label": "Saturated",
            "quantity": 87.695522621,
            "unit": "g"
          },
          "FAMS": {
            "label": "Monounsaturated",
            "quantity": 112.18473539000001,
            "unit": "g"
          },
          "FAPU": {
            "label": "Polyunsaturated",
            "quantity": 25.662398405000005,
            "unit": "g"
          },
          "CHOCDF": {
            "label": "Carbs",
            "quantity": 8.86284,
            "unit": "g"
          },
          "FIBTG": {
            "label": "Fiber",
            "quantity": 0.11025,
            "unit": "g"
          },
          "SUGAR": {
            "label": "Sugars",
            "quantity": 8.406825,
            "unit": "g"
          },
          "SUGAR.added": {
            "label": "Sugars, added",
            "quantity": 8.3832,
            "unit": "g"
          },
          "PROCNT": {
            "label": "Protein",
            "quantity": 42.552532358,
            "unit": "g"
          },
          "CHOLE": {
            "label": "Cholesterol",
            "quantity": 326.5865064,
            "unit": "mg"
          },
          "NA": {
            "label": "Sodium",
            "quantity": 1076.7957705876,
            "unit": "mg"
          },
          "CA": {
            "label": "Calcium",
            "quantity": 33.114874655954964,
            "unit": "mg"
          },
          "MG": {
            "label": "Magnesium",
            "quantity": 22.01068463983146,
            "unit": "mg"
          },
          "K": {
            "label": "Potassium",
            "quantity": 858.2798032186518,
            "unit": "mg"
          },
          "FE": {
            "label": "Iron",
            "quantity": 3.0675769711443808,
            "unit": "mg"
          },
          "ZN": {
            "label": "Zinc",
            "quantity": 4.6802811579831465,
            "unit": "mg"
          },
          "P": {
            "label": "Phosphorus",
            "quantity": 495.1192596000001,
            "unit": "mg"
          },
          "VITA_RAE": {
            "label": "Vitamin A",
            "quantity": 14.279771100000001,
            "unit": "µg"
          },
          "VITC": {
            "label": "Vitamin C",
            "quantity": 1.4416271100000002,
            "unit": "mg"
          },
          "THIA": {
            "label": "Thiamin (B1)",
            "quantity": 1.8028197852000003,
            "unit": "mg"
          },
          "RIBF": {
            "label": "Riboflavin (B2)",
            "quantity": 1.1027230354000002,
            "unit": "mg"
          },
          "NIA": {
            "label": "Niacin (B3)",
            "quantity": 21.126516933900003,
            "unit": "mg"
          },
          "VITB6A": {
            "label": "Vitamin B6",
            "quantity": 0.594237581,
            "unit": "mg"
          },
          "FOLDFE": {
            "label": "Folate equivalent (total)",
            "quantity": 4.640923700000001,
            "unit": "µg"
          },
          "FOLFD": {
            "label": "Folate (food)",
            "quantity": 4.640923700000001,
            "unit": "µg"
          },
          "VITB12": {
            "label": "Vitamin B12",
            "quantity": 3.810175908,
            "unit": "µg"
          },
          "TOCPHA": {
            "label": "Vitamin E",
            "quantity": 1.8039752430000002,
            "unit": "mg"
          },
          "VITK1": {
            "label": "Vitamin K",
            "quantity": 0.05670000000000001,
            "unit": "µg"
          },
          "WATER": {
            "label": "Water",
            "quantity": 166.7409447059663,
            "unit": "g"
          }
        },
        "totalDaily": {
          "ENERC_KCAL": {
            "label": "Energy",
            "quantity": 119.30269883000001,
            "unit": "%"
          },
          "FAT": {
            "label": "Fat",
            "quantity": 370.2817697492308,
            "unit": "%"
          },
          "FASAT": {
            "label": "Saturated",
            "quantity": 438.477613105,
            "unit": "%"
          },
          "CHOCDF": {
            "label": "Carbs",
            "quantity": 2.95428,
            "unit": "%"
          },
          "FIBTG": {
            "label": "Fiber",
            "quantity": 0.441,
            "unit": "%"
          },
          "PROCNT": {
            "label": "Protein",
            "quantity": 85.105064716,
            "unit": "%"
          },
          "CHOLE": {
            "label": "Cholesterol",
            "quantity": 108.8621688,
            "unit": "%"
          },
          "NA": {
            "label": "Sodium",
            "quantity": 44.86649044115,
            "unit": "%"
          },
          "CA": {
            "label": "Calcium",
            "quantity": 3.3114874655954964,
            "unit": "%"
          },
          "MG": {
            "label": "Magnesium",
            "quantity": 5.240639199959872,
            "unit": "%"
          },
          "K": {
            "label": "Potassium",
            "quantity": 18.261272408907484,
            "unit": "%"
          },
          "FE": {
            "label": "Iron",
            "quantity": 17.042094284135448,
            "unit": "%"
          },
          "ZN": {
            "label": "Zinc",
            "quantity": 42.548010527119516,
            "unit": "%"
          },
          "P": {
            "label": "Phosphorus",
            "quantity": 70.73132280000002,
            "unit": "%"
          },
          "VITA_RAE": {
            "label": "Vitamin A",
            "quantity": 1.5866412333333333,
            "unit": "%"
          },
          "VITC": {
            "label": "Vitamin C",
            "quantity": 1.6018079000000003,
            "unit": "%"
          },
          "THIA": {
            "label": "Thiamin (B1)",
            "quantity": 150.23498210000002,
            "unit": "%"
          },
          "RIBF": {
            "label": "Riboflavin (B2)",
            "quantity": 84.82484887692308,
            "unit": "%"
          },
          "NIA": {
            "label": "Niacin (B3)",
            "quantity": 132.040730836875,
            "unit": "%"
          },
          "VITB6A": {
            "label": "Vitamin B6",
            "quantity": 45.71058315384615,
            "unit": "%"
          },
          "FOLDFE": {
            "label": "Folate equivalent (total)",
            "quantity": 1.1602309250000002,
            "unit": "%"
          },
          "VITB12": {
            "label": "Vitamin B12",
            "quantity": 158.7573295,
            "unit": "%"
          },
          "TOCPHA": {
            "label": "Vitamin E",
            "quantity": 12.026501620000001,
            "unit": "%"
          },
          "VITK1": {
            "label": "Vitamin K",
            "quantity": 0.04725000000000001,
            "unit": "%"
          }
        },
        "digest": [
          {
            "label": "Fat",
            "tag": "FAT",
            "schemaOrgTag": "fatContent",
            "total": 240.68315033700003,
            "hasRDI": true,
            "daily": 370.2817697492308,
            "unit": "g",
            "sub": [
              {
                "label": "Saturated",
                "tag": "FASAT",
                "schemaOrgTag": "saturatedFatContent",
                "total": 87.695522621,
                "hasRDI": true,
                "daily": 438.477613105,
                "unit": "g"
              },
              {
                "label": "Trans",
                "tag": "FATRN",
                "schemaOrgTag": "transFatContent",
                "total": 0.0,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Monounsaturated",
                "tag": "FAMS",
                "schemaOrgTag": null,
                "total": 112.18473539000001,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Polyunsaturated",
                "tag": "FAPU",
                "schemaOrgTag": null,
                "total": 25.662398405000005,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              }
            ]
          },
          {
            "label": "Carbs",
            "tag": "CHOCDF",
            "schemaOrgTag": "carbohydrateContent",
            "total": 8.86284,
            "hasRDI": true,
            "daily": 2.95428,
            "unit": "g",
            "sub": [
              {
                "label": "Carbs (net)",
                "tag": "CHOCDF.net",
                "schemaOrgTag": null,
                "total": 8.75259,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Fiber",
                "tag": "FIBTG",
                "schemaOrgTag": "fiberContent",
                "total": 0.11025,
                "hasRDI": true,
                "daily": 0.441,
                "unit": "g"
              },
              {
                "label": "Sugars",
                "tag": "SUGAR",
                "schemaOrgTag": "sugarContent",
                "total": 8.406825,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              },
              {
                "label": "Sugars, added",
                "tag": "SUGAR.added",
                "schemaOrgTag": null,
                "total": 8.3832,
                "hasRDI": false,
                "daily": 0.0,
                "unit": "g"
              }
            ]
          },
          {
            "label": "Protein",
            "tag": "PROCNT",
            "schemaOrgTag": "proteinContent",
            "total": 42.552532358,
            "hasRDI": true,
            "daily": 85.105064716,
            "unit": "g"
          },
          {
            "label": "Cholesterol",
            "tag": "CHOLE",
            "schemaOrgTag": "cholesterolContent",
            "total": 326.5865064,
            "hasRDI": true,
            "daily": 108.8621688,
            "unit": "mg"
          },
          {
            "label": "Sodium",
            "tag": "NA",
            "schemaOrgTag": "sodiumContent",
            "total": 1076.7957705876,
            "hasRDI": true,
            "daily": 44.86649044115,
            "unit": "mg"
          },
          {
            "label": "Calcium",
            "tag": "CA",
            "schemaOrgTag": null,
            "total": 33.114874655954964,
            "hasRDI": true,
            "daily": 3.3114874655954964,
            "unit": "mg"
          },
          {
            "label": "Magnesium",
            "tag": "MG",
            "schemaOrgTag": null,
            "total": 22.01068463983146,
            "hasRDI": true,
            "daily": 5.240639199959872,
            "unit": "mg"
          },
          {
            "label": "Potassium",
            "tag": "K",
            "schemaOrgTag": null,
            "total": 858.2798032186518,
            "hasRDI": true,
            "daily": 18.261272408907484,
            "unit": "mg"
          },
          {
            "label": "Iron",
            "tag": "FE",
            "schemaOrgTag": null,
            "total": 3.0675769711443808,
            "hasRDI": true,
            "daily": 17.042094284135448,
            "unit": "mg"
          },
          {
            "label": "Zinc",
            "tag": "ZN",
            "schemaOrgTag": null,
            "total": 4.6802811579831465,
            "hasRDI": true,
            "daily": 42.548010527119516,
            "unit": "mg"
          },
          {
            "label": "Phosphorus",
            "tag": "P",
            "schemaOrgTag": null,
            "total": 495.1192596000001,
            "hasRDI": true,
            "daily": 70.73132280000002,
            "unit": "mg"
          },
          {
            "label": "Vitamin A",
            "tag": "VITA_RAE",
            "schemaOrgTag": null,
            "total": 14.279771100000001,
            "hasRDI": true,
            "daily": 1.5866412333333333,
            "unit": "µg"
          },
          {
            "label": "Vitamin C",
            "tag": "VITC",
            "schemaOrgTag": null,
            "total": 1.4416271100000002,
            "hasRDI": true,
            "daily": 1.6018079000000003,
            "unit": "mg"
          },
          {
            "label": "Thiamin (B1)",
            "tag": "THIA",
            "schemaOrgTag": null,
            "total": 1.8028197852000003,
            "hasRDI": true,
            "daily": 150.23498210000002,
            "unit": "mg"
          },
          {
            "label": "Riboflavin (B2)",
            "tag": "RIBF",
            "schemaOrgTag": null,
            "total": 1.1027230354000002,
            "hasRDI": true,
            "daily": 84.82484887692308,
            "unit": "mg"
          },
          {
            "label": "Niacin (B3)",
            "tag": "NIA",
            "schemaOrgTag": null,
            "total": 21.126516933900003,
            "hasRDI": true,
            "daily": 132.040730836875,
            "unit": "mg"
          },
          {
            "label": "Vitamin B6",
            "tag": "VITB6A",
            "schemaOrgTag": null,
            "total": 0.594237581,
            "hasRDI": true,
            "daily": 45.71058315384615,
            "unit": "mg"
          },
          {
            "label": "Folate equivalent (total)",
            "tag": "FOLDFE",
            "schemaOrgTag": null,
            "total": 4.640923700000001,
            "hasRDI": true,
            "daily": 1.1602309250000002,
            "unit": "µg"
          },
          {
            "label": "Folate (food)",
            "tag": "FOLFD",
            "schemaOrgTag": null,
            "total": 4.640923700000001,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "µg"
          },
          {
            "label": "Folic acid",
            "tag": "FOLAC",
            "schemaOrgTag": null,
            "total": 0.0,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "µg"
          },
          {
            "label": "Vitamin B12",
            "tag": "VITB12",
            "schemaOrgTag": null,
            "total": 3.810175908,
            "hasRDI": true,
            "daily": 158.7573295,
            "unit": "µg"
          },
          {
            "label": "Vitamin D",
            "tag": "VITD",
            "schemaOrgTag": null,
            "total": 0.0,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "µg"
          },
          {
            "label": "Vitamin E",
            "tag": "TOCPHA",
            "schemaOrgTag": null,
            "total": 1.8039752430000002,
            "hasRDI": true,
            "daily": 12.026501620000001,
            "unit": "mg"
          },
          {
            "label": "Vitamin K",
            "tag": "VITK1",
            "schemaOrgTag": null,
            "total": 0.05670000000000001,
            "hasRDI": true,
            "daily": 0.04725000000000001,
            "unit": "µg"
          },
          {
            "label": "Sugar alcohols",
            "tag": "Sugar.alcohol",
            "schemaOrgTag": null,
            "total": 0.0,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "g"
          },
          {
            "label": "Water",
            "tag": "WATER",
            "schemaOrgTag": null,
            "total": 166.7409447059663,
            "hasRDI": false,
            "daily": 0.0,
            "unit": "g"
          }
        ]
      },
      "bookmarked": false,
      "bought": false
    }
  ]
}

I am just parsing a few elements in the response by using the mentioned POJO class above. I am seeing the component is loading properly from the parent component but it's not displaying data inside the div as the API call is not being made. I am seeing the error log displayed in the console but the API call is not showing up in the network tab.

Body:
You have some misunderstandings regarding the classes in typescript. Classes in the typescript are not some magic. You have only defined the class and expect the angular to automatically map the raw response to the actual class structure. They don't. You have to manually map the raw response to the actual class defined structure.

  getRecipeInfo(): Observable<RecipeGlobal>{
         return this.http.get<RecipeGlobal>(this.searchUrl)
         .pipe(
           map(res => this.mapRawResponse(res))
           catchError(_ => {console.log("error"); return [];})
         );
  }

    private mapRawResponse(rawResponse): RecipeGlobal {
          //... your code to map the response to Recipe.
    }

If you don't want to map the response, then change the structure of your class definition to match the raw response.

As for the no API calls being shown in the Network tab, check the filters on it, you may using some filters (css/Img/Media/etc). Switch it to xhr/All to see.

Updated with proper class

Use this class instead to get the type support:

export interface RecipeGlobal {
    q:     string;
    from:  number;
    to:    number;
    more:  boolean;
    count: number;
    hits:  Hit[];
}

export interface Hit {
    recipe:     Recipe;
    bookmarked: boolean;
    bought:     boolean;
}

export interface Recipe {
    uri:             string;
    label:           string;
    image:           string;
    source:          string;
    url:             string;
    shareAs:         string;
    yield:           number;
    dietLabels:      string[];
    healthLabels:    string[];
    cautions:        any[];
    ingredientLines: string[];
    ingredients:     Ingredient[];
    calories:        number;
    totalWeight:     number;
    totalTime:       number;
    totalNutrients:  { [key: string]: Total };
    totalDaily:      { [key: string]: Total };
    digest:          Digest[];
}

export interface Digest {
    label:        string;
    tag:          string;
    schemaOrgTag: null | string;
    total:        number;
    hasRDI:       boolean;
    daily:        number;
    unit:         Unit;
    sub?:         Digest[];
}

export enum Unit {
    Empty = "%",
    G = "g",
    Kcal = "kcal",
    Mg = "mg",
    Μg = "µg",
}

export interface Ingredient {
    text:   string;
    weight: number;
}

export interface Total {
    label:    string;
    quantity: number;
    unit:     Unit;
}


来源: stackexchange

问:
How do people host Spring Boot apps with WebFlux on Reactor Netty in production?
I know it's a vague question but that's because I am not clear enough on what people are doing to ask anything more specific. I currently run my own apps with the embedded reactor netty server for development and basically push the embedded server inside a jar to cloud foundry to run the embedded server in production.

What are the other ways out there to set up a production environment for reactive reactor netty apps that people are using, or any documentation you might have seen?

答:
I'm no sure that there is any difference between hosting the reactive spring-webflux application and regular applications.

Spring boot creates a jar with everything bundled inside (netty or more old-school tomcat) - it doesn't matter.

Then you can take this and run it "as is" on your server (on-premise, cloud ec2 style whatever you have, this really depends on your organization) directly with java -jar app.jar

Or, if you have more advanced needs/setup:

"Containerize" the application and create a docker (usually, although there are alternatives) image that runs the spring boot application. and then deploy it on kubernetes cluster, for example. At this point you should really consult with your DevOps people so that they'll tell you what is the way of deployment in your organization.
Besides kubernetes cluster there are many other alternatives:
 - cloud provider specific solutions, like ECS or Fargate in amazon AWS
 - Docker Swarm to name a few

All these solutions are pretty advanced, allow auto-scaling, advanced liveness monitoring and so forth. As an organization you usually pick the one that meets your needs

ContentLicense: CC BY-SA 4.0


问:
How to display Laravel Relationship data in a Blade View, when using groupBy() in query
I'm making and inventory system for basic parts, that provides coverage for more than one company location. So my inventory table has parts information such as part_number and description as well as a location_id that foreign keys into a locations table. I have several stock items with the same part number, but have varying inventory levels at each location. I want to group the inventory by location, and then list all of the inventory at that location before cycling through the other locations and doing the same thing.

Here is what I have in my controller:

```<code>$inventory = Inventory::where('part_number', '12345')->get();

    // dd($inventory);

$inventory_grouped_by_location = $inventory->groupBy('location_id');

    // dd($inventory_grouped_by_location);

return view('inventory.show', compact('inventory_grouped_by_location');
</code>```

Here is what I have in my Inventory model:

```<code>public function location()
{
    return $this->belongsTo(Location::class);
}
</code>```

Here is what I have in my Location model:

```<code>public function parts_inventory()
{
    return $this->hasMany(Inventory::class);
}
</code>```

Here is what I have tried in my view:

```<code>@foreach($inventory_grouped_by_location as $location)

<p>Location: {{ $location->name }}</p>

    @foreach($location as $inventory)

        <p>Part Number: {{ $inventory->part_number }}</p>

    @endforeach

@endforeach
</code>```

The above code throws and error because I'm trying to access the location relationship, but I've only got the location->id from the inventory table. I've tried to access the relationship like this $location[$key]->name but no joy.

答:
In your controller, replace this query

```<code>$inventory_grouped_by_location = $inventory->groupBy('location_id');
</code>```

with this

```<code>$inventory_grouped_by_location = Inventory::where('part_number', '12345')->with('location')->groupBy('location_id')->get();
</code>```

In your blade, you can do something like this:

```<code>@foreach($inventory_grouped_by_location as $inventory)

<p>Location: {{ $inventory->location->name }}</p>

    <p>Part Number: {{ $inventory->part_number }}</p>

@endforeach
</code>```

You can't loop through $inventory again since you already are at an index of the collection $inventory_grouped_by_location.

If you are looking to make the nested loop as specified in your question, you probably don't need groupBy() at all.

In your controller method:

```<code>$locations = Location::all();
$inventory = Inventory::where('part_number', 123456)->get();
</code>```

And in your blade:

```<code>@foreach($locations as $location)

<p>Location: {{ $location->name }}</p>

    @foreach($inventory as $item)
        @if($item->location_id == $location->id)
        <p>Part Number: {{ $item->part_number }}</p>
        @endif
    @endforeach

@endforeach
</code>```

Hope it helps!

Body:
I'm making and inventory system for basic parts, that provides coverage for more than one company location. So my inventory table has parts information such as part_number and description as well as a location_id that foreign keys into a locations table. I have several stock items with the same part number, but have varying inventory levels at each location. I want to group the inventory by location, and then list all of the inventory at that location before cycling through the other locations and doing the same thing.

Here is what I have in my controller:

$inventory = Inventory::where('part_number', '12345')->get();

    // dd($inventory);

$inventory_grouped_by_location = $inventory->groupBy('location_id');

    // dd($inventory_grouped_by_location);

return view('inventory.show', compact('inventory_grouped_by_location');

Here is what I have in my Inventory model:

public function location()
{
    return $this->belongsTo(Location::class);
}

Here is what I have in my Location model:

public function parts_inventory()
{
    return $this->hasMany(Inventory::class);
}

Here is what I have tried in my view:

@foreach($inventory_grouped_by_location as $location)

Location: {{ $location->name }}

    @foreach($location as $inventory)

Part Number: {{ $inventory->part_number }}

    @endforeach

@endforeach

The above code throws and error because I'm trying to access the location relationship, but I've only got the location->id from the inventory table. I've tried to access the relationship like this $location[$key]->name but no joy.

Body:
In your controller, replace this query

$inventory_grouped_by_location = $inventory->groupBy('location_id');

with this

$inventory_grouped_by_location = Inventory::where('part_number', '12345')->with('location')->groupBy('location_id')->get();

In your blade, you can do something like this:

@foreach($inventory_grouped_by_location as $inventory)

<p>Location: {{ $inventory->location->name }}</p>

    <p>Part Number: {{ $inventory->part_number }}</p>

@endforeach

You can't loop through $inventory again since you already are at an index of the collection $inventory_grouped_by_location.

If you are looking to make the nested loop as specified in your question, you probably don't need groupBy() at all.

In your controller method:

$locations = Location::all();
$inventory = Inventory::where('part_number', 123456)->get();

And in your blade:

@foreach($locations as $location)

<p>Location: {{ $location->name }}</p>

    @foreach($inventory as $item)
        @if($item->location_id == $location->id)
        <p>Part Number: {{ $item->part_number }}</p>
        @endif
    @endforeach

@endforeach

Hope it helps!


问:
vue js : How to set focus on disabled input field
```<code><b-row v-if="detailsEditable">
                <b-col cols="6">
                  <b-form-group label="First name">
                    <b-form-input
                      ref="firstName"
                      v-model="userDetails.first_name"
                      :disabled="!detailsEditable"

                    ></b-form-input>
                  </b-form-group>
                </b-col>
                <b-col cols="6" class="pl-0">
                  <b-form-group label="Last name">
                    <b-form-input
                      v-model="userDetails.last_name"
                      :disabled="!detailsEditable"
                    ></b-form-input>
                  </b-form-group>
                </b-col>
              </b-row>
              <b-row v-else>
                <b-col cols="12">
                  <b-form-group label="Full name">
                    <div @click="enableField('name')">
                      <b-form-input
                        ref="name"
                        :value="
                          userDetails.first_name + ' ' + userDetails.last_name
                        "
                        :disabled="!detailsEditable"
                      ></b-form-input>
                    </div>
                  </b-form-group>
                </b-col>
              </b-row>
<script>
export default {
  data() {
detailsEditable: false,
}
}
</script>
</code>```

When click on 'Full name' field, I need to set focus on 'First Name' input box, which is disabled and show only if detailsEditable =true

I set focus in the method enableField. But it not works using $refs.

```<code>enableField(value) {
    const vm = this
    vm.detailsEditable = true
    vm.$refs.firstName.focus()
}
</code>```

答:
Try this:

```<code>enableField (value) {
  const vm = this
  vm.detailsEditable = true
  vm.$nextTick(() => {
    vm.$refs.firstName.focus()
  })
}
</code>```

I think issue is the timing of Vue’s rendering. Vue buffers changes and essentially renders asynchronously. For this reason, you will likely want to call focus in nextTick.

Body:
When click on 'Full name' field, I need to set focus on 'First Name' input box, which is disabled and show only if detailsEditable =true

I set focus in the method enableField. But it not works using $refs.

enableField(value) {
    const vm = this
    vm.detailsEditable = true
    vm.$refs.firstName.focus()
}

Body:
Try this:

enableField (value) {
  const vm = this
  vm.detailsEditable = true
  vm.$nextTick(() => {
    vm.$refs.firstName.focus()
  })
}

I think issue is the timing of Vue’s rendering. Vue buffers changes and essentially renders asynchronously. For this reason, you will likely want to call focus in nextTick.


问:
Nested calc operations
Hopefully this is quite simple. I want to use the CSS calc operation to perform two calculations:

I want to set my width to the equivalent of

```<code>(100% / 7) - 2
</code>```

However if I try to perform more than one operation in a CSS calc operation, it fails:

```<code>width: calc((100% / 7) - 2);
</code>```

How can I perform multiple calc operations in one CSS statement?

答:
I also had a lot of headache when I tried to do that, but fortunately there's an alternative. Instead of writing it all in a single line, you could also use pure css variables using var(), which aside from solving this problem, is also much more readable! Here's an example of how I used it:

```<code>#wrapper .leftside .week .superior {
    --wholeWidth: calc(157px * 3);
    --remaining: calc(100% - var(--wholeWidth));
    margin: 0 calc(var(--remaining) / 6);
}
</code>```

I found it under the "Nested calc() with CSS Variables" in the MDN docs.

ContentLicense: CC BY-SA 3.0

Title: Nested calc operations

Body:
Hopefully this is quite simple. I want to use the CSS calc operation to perform two calculations:

I want to set my width to the equivalent of

(100% / 7) - 2

However if I try to perform more than one operation in a CSS calc operation, it fails:

width: calc((100% / 7) - 2);

How can I perform multiple calc operations in one CSS statement?

Body:
I also had a lot of headache when I tried to do that, but fortunately there's an alternative. Instead of writing it all in a single line, you could also use pure css variables using var(), which aside from solving this problem, is also much more readable! Here's an example of how I used it:

#wrapper .leftside .week .superior {
    --wholeWidth: calc(157px * 3);
    --remaining: calc(100% - var(--wholeWidth));
    margin: 0 calc(var(--remaining) / 6);
}

I found it under the "Nested calc() with CSS Variables" in the MDN docs.


问:
reversing the order of elements in Array
i'm  currently stuck on an assignment where I have to reverse the order of the elements in my Array.
But the problem is that I only get the 10 10 times and not 10 9 8...</p>
```<code>package JavaSection4;

public class Assignment4Nr2 {

    public static void main(String[] args) {

        int[] ranNum = new int[10];

        ranNum[0] = 1;
        ranNum[1] = 2;
        ranNum[2] = 3;
        ranNum[3] = 4;
        ranNum[4] = 5;
        ranNum[5] = 6;
        ranNum[6] = 7;
        ranNum[7] = 8;
        ranNum[8] = 9;
        ranNum[9] = 10;

        for(int i = 0; i < ranNum.length; i++) {

            int l = 0;

            l = ranNum.length - 1;

            System.out.println(ranNum[l]);
        }
    }
}
</code>```

答:
```<code>public class ReverseArray {
public static void main(String[] args) {
    //Initialize array
    int [] arr = new int [] {1, 2, 3, 4, 5};
    System.out.println("Original array: ");
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
    System.out.println();
    System.out.println("Array in reverse order: ");
    //Loop through the array in reverse order
    for (int i = arr.length-1; i >= 0; i--) {
        System.out.print(arr[i] + " ");
    }
}
</code>```

}

should do the trick.

Body:
i'm  currently stuck on an assignment where I have to reverse the order of the elements in my Array.
But the problem is that I only get the 10 10 times and not 10 9 8...

package JavaSection4;

public class Assignment4Nr2 {

    public static void main(String[] args) {

        int[] ranNum = new int[10];

        ranNum[0] = 1;
        ranNum[1] = 2;
        ranNum[2] = 3;
        ranNum[3] = 4;
        ranNum[4] = 5;
        ranNum[5] = 6;
        ranNum[6] = 7;
        ranNum[7] = 8;
        ranNum[8] = 9;
        ranNum[9] = 10;

        for(int i = 0; i < ranNum.length; i++) {

            int l = 0;

            l = ranNum.length - 1;

            System.out.println(ranNum[l]);
        }
    }
}

Body:
public class ReverseArray {
public static void main(String[] args) {
    //Initialize array
    int [] arr = new int [] {1, 2, 3, 4, 5};
    System.out.println("Original array: ");
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
    System.out.println();
    System.out.println("Array in reverse order: ");
    //Loop through the array in reverse order
    for (int i = arr.length-1; i >= 0; i--) {
        System.out.print(arr[i] + " ");
    }
}

}

should do the trick.


问:
GitLab all repository ssh clone url shows wrong path
GitLab Web all repository SSH clone URL shows wrong path.

Wrong path: ssh://git@ssh.gitlab.domain.com:443/test_group/test30-jan-2020.git

After modified With following command able to clone on terminal.

```<code>git clone git@gitlab.domain.com:test_group/test30-jan-2020.git
</code>```

To correct the same Under Admin--> Settings---> couldn't find option to change it to proper clone url. Any workaround will be highly appreciated.

答:
It should be, as documented in "Configuring the external URL for GitLab" in external_url or your /etc/gitlab/gitlab.rb

Check first  Admin Area > Settings > General > Sign-in restrictions

Or, for omnibus, in gitlab-config-template/gitlab.rb.template.

The OP Kishore mentions in the comments:

In /etc/gitlab.rb file, Gitlab_rails['gitlab_shell_ssh_port'] = was enabled.

  I have disabled and restarted. It is showing correct path.

(You could see that setting used in sameersbn/docker-gitlab issue 38 )

Body:
GitLab Web all repository SSH clone URL shows wrong path.

Wrong path: ssh://git@ssh.gitlab.domain.com:443/test_group/test30-jan-2020.git

After modified With following command able to clone on terminal.

git clone git@gitlab.domain.com:test_group/test30-jan-2020.git

To correct the same Under Admin--> Settings---> couldn't find option to change it to proper clone url. Any workaround will be highly appreciated.


问:
how to generate a php image for src
I would like to use:

```<code>src="my_generated_image_from_php.jpg"
</code>```

instead of

src="my_php_image.php"

How do I do it?

my_php_image.php like:

```<code><?php
     ......
     Header('Content-type: image/png');
     imagepng($im2);
     imagedestroy($im2);
     ......
?>
</code>```

答:
Here's how Drupal does it.  Your URL to the image looks like index.php?q=some/path/to/the/image.jpg but if your webserver is set up right these simple rules:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
</code>```

Now PHP can extract the request path with

```<code>$request_path = strtok($_SERVER['REQUEST_URI'], '?')
$base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
// Unescape and strip $base_path prefix, leaving q without a leading slash.
$path = substr(urldecode($request_path), $base_path_len + 1);
</code>```

Once you have done this as BraedenP says you just need the correct HTTP headers and off you go.

Title: how to generate a php image for src

Body:
I would like to use:

src="my_generated_image_from_php.jpg"

instead of

src="my_php_image.php"

How do I do it?

my_php_image.php like:

<?php
     ......
     Header('Content-type: image/png');
     imagepng($im2);
     imagedestroy($im2);
     ......
?>

Body:
Here's how Drupal does it.  Your URL to the image looks like index.php?q=some/path/to/the/image.jpg but if your webserver is set up right these simple rules:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

Now PHP can extract the request path with

$request_path = strtok($_SERVER['REQUEST_URI'], '?')
$base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
// Unescape and strip $base_path prefix, leaving q without a leading slash.
$path = substr(urldecode($request_path), $base_path_len + 1);

Once you have done this as BraedenP says you just need the correct HTTP headers and off you go.


问:
How can I set up Prettier in VSCode settings to conditionally apply single quotes by file type?
I'm trying to set up Prettier in VSCode settings so that for all file types except JS it will default to double quotes.

I've disabled ESLint to make sure it's not the problem.  I've also check Prettier documentation on configuration overrides in JSON.  But my settings don't seem to work.

```<code>  "prettier": {
    "singleQuote": false,
    "overrides": [
      {
        "files": "*.js",
        "options": {
          "singleQuote": true
        }
      }
    ]
  }
</code>```

When I save a CSS file I expect to see double quotes and I do.
When I save a JS file I expect to see single quotes (when there's no apostrophes used in the string) but it sets double quotes on all strings.

答:
To use single quotes for JavaScript but double quotes for CSS, SCSS, and HTML, in your project root directory, add a .prettierrc file with this JSON:

```<code>{
  "singleQuote": true,
  "overrides": [
    {
      "files": ["**/*.css", "**/*.scss", "**/*.html"],
      "options": {
        "singleQuote": false
      }
    }
  ]
}
</code>```

(Bonus info: The ** is a glob character and represents any number of subfolders within the current folder.)

Body:
I'm trying to set up Prettier in VSCode settings so that for all file types except JS it will default to double quotes.

I've disabled ESLint to make sure it's not the problem.  I've also check Prettier documentation on configuration overrides in JSON.  But my settings don't seem to work.

  "prettier": {
    "singleQuote": false,
    "overrides": [
      {
        "files": "*.js",
        "options": {
          "singleQuote": true
        }
      }
    ]
  }

When I save a CSS file I expect to see double quotes and I do.
When I save a JS file I expect to see single quotes (when there's no apostrophes used in the string) but it sets double quotes on all strings.

Body:
To use single quotes for JavaScript but double quotes for CSS, SCSS, and HTML, in your project root directory, add a .prettierrc file with this JSON:

{
  "singleQuote": true,
  "overrides": [
    {
      "files": ["**/*.css", "**/*.scss", "**/*.html"],
      "options": {
        "singleQuote": false
      }
    }
  ]
}

(Bonus info: The ** is a glob character and represents any number of subfolders within the current folder.)


问:
Runtime analysis of dependent nested for
0

Here is the algorithm:

```<code>int sum = 0
for (int i = 2N; i > 0; i = i / 4)
  for (int j = 0; j < i; j+=2)
    sum++
  end for
end for
</code>```

I figured this would be linearithmic, but it's just linear. I would appreciate seeing a formalized summation and not a qualitative explanation. I have tried doing this but I fail to get linear runtime.

答:
Cut it in pieces:

```<code>int sum = 0
</code>```

Here you have O(1).

```<code>for (int i = 2N; i > 0; i = i / 4)
</code>```

How many times will this run? Let's say it will run k times and evaluate k:

2N / 4^k = 1 => 2N = 4^k => k = log4(2N). To simplify, let's just call k = lg(N).

```<code>for (int j = 0; j < i; j+=2)
    sum++
end for
</code>```

In the first case, this for goes until N, then N/4, then N/16, etc.

What this gives you is:

∑(N / 4^i), i = 0 ... k =

N * ∑ 1/4^i, i = 0 ... k

∑ 1/4^i, i = 0 ... k is a series that is smaller than 4/3, since it stops in k = lg(n) because the outer loop just runs lg(n) times.

Hence, the complexity is O(X < 4/3 * N), therefore, linear.

Body:
0

Here is the algorithm:

int sum = 0
for (int i = 2N; i > 0; i = i / 4)
  for (int j = 0; j < i; j+=2)
    sum++
  end for
end for

I figured this would be linearithmic, but it's just linear. I would appreciate seeing a formalized summation and not a qualitative explanation. I have tried doing this but I fail to get linear runtime.

Body:
Cut it in pieces:

int sum = 0

Here you have O(1).

for (int i = 2N; i > 0; i = i / 4)

How many times will this run? Let's say it will run k times and evaluate k:

2N / 4^k = 1 => 2N = 4^k => k = log4(2N). To simplify, let's just call k = lg(N).

for (int j = 0; j < i; j+=2)
    sum++
end for

In the first case, this for goes until N, then N/4, then N/16, etc.

What this gives you is:

∑(N / 4^i), i = 0 ... k =

N * ∑ 1/4^i, i = 0 ... k

∑ 1/4^i, i = 0 ... k is a series that is smaller than 4/3, since it stops in k = lg(n) because the outer loop just runs lg(n) times.

Hence, the complexity is O(X < 4/3 * N), therefore, linear.


问:
CORS problem with axios from a Vue app to a PHP API running on WAMP
I have trouble making an XHR request with axios from a Vue app to a PHP API running on WAMP.

The error message is the following :

Access to XMLHttpRequest at 'http://localhost/myapp/api/test/1' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As you can see, it's a problem with CORS. After some documentation, here is what I have been doing to fix it (still not working).

Axios call :

```<code>axios({
  method: 'get',
  url: 'http://localhost/myapp/api/test/1',
  data: JSON.stringify({}),
  headers: { 'Content-Type': 'application/json', },
  crossdomain: true,
});
</code>```

If I visit http://localhost/myapp/api/test/1 in my web browser, I got my response.

I attempted putting this line of code in my PHP API, in my entry point (index.php)

```<code>header('Access-Control-Allow-Origin: *');
</code>```

I configured WAMP :

Changed httpd-vhosts.conf and httpd.conf

```<code># Virtual Hosts

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    Header set Access-Control-Allow-Origin "*"
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>
</code>```

Activated the "headers_module" in apache's modules

Rebooted everything, cleared my cache, tried from another browser ...

Still not working, am I missing something ?

答:
Try this extension for cross origin.

https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc

Body:
I have trouble making an XHR request with axios from a Vue app to a PHP API running on WAMP.

The error message is the following :

Access to XMLHttpRequest at 'http://localhost/myapp/api/test/1' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As you can see, it's a problem with CORS. After some documentation, here is what I have been doing to fix it (still not working).

Axios call :

axios({
  method: 'get',
  url: 'http://localhost/myapp/api/test/1',
  data: JSON.stringify({}),
  headers: { 'Content-Type': 'application/json', },
  crossdomain: true,
});

If I visit http://localhost/myapp/api/test/1 in my web browser, I got my response.

I attempted putting this line of code in my PHP API, in my entry point (index.php)

header('Access-Control-Allow-Origin: *');

I configured WAMP :

Changed httpd-vhosts.conf and httpd.conf

# Virtual Hosts

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    Header set Access-Control-Allow-Origin "*"
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>

Activated the "headers_module" in apache's modules

Rebooted everything, cleared my cache, tried from another browser ...

Still not working, am I missing something ?


问:
Extract a string of words between multiple specific words in R
I have a long string that includes one or multiple keywords, "Realm" in this case. I have been using gsub, but that only takes the words after the last of the keywords.

so the string could look like:

...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...

or

...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome...

I have been using the function:

```<code>Realm_fun<-function(x){gsub('^.*Realm -\\s*|\\s*IUCN Ecosystem.*$', '', x)}
</code>```

then using lapply to fun it on all of the strings.

what can I do to get Afrotropical for the first string and Afrotropical , Neotropical for the second?

答:
Use base functions gregexpr and regmatches.

```<code>library(magrittr)

test<-c("...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...","...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome...")

test %>% gregexpr("(?<=(Realm - ))[a-zA-Z]+", ., perl = T) %>% regmatches(x = test)

#[[1]]
#[1] "Afrotropical"

#[[2]]
#[1] "Afrotropical" "Neotropical"
</code>```

Body:
I have a long string that includes one or multiple keywords, "Realm" in this case. I have been using gsub, but that only takes the words after the last of the keywords.

so the string could look like:

...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...

or

...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome...

I have been using the function:

Realm_fun<-function(x){gsub('^.*Realm -\\s*|\\s*IUCN Ecosystem.*$', '', x)}

then using lapply to fun it on all of the strings.

what can I do to get Afrotropical for the first string and Afrotropical , Neotropical for the second?

Body:
Use base functions gregexpr and regmatches.

library(magrittr)

test<-c("...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...","...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome...")

test %>% gregexpr("(?<=(Realm - ))[a-zA-Z]+", ., perl = T) %>% regmatches(x = test)

#[[1]]
#[1] "Afrotropical"

#[[2]]
#[1] "Afrotropical" "Neotropical"


问:
Automatically insert a data to database in certain cases in laravel
I am new to laravel. I want to know is there any particular better option to use in the following case in laravel. For an example I have a table called product and another table called productlog. While a product is created / updated / deleted in those cases I have to insert a log in productlog table. I know, I can insert these data directly in the controller while these actions happening. Except this laravel has any better feature to use in this case?</p>

答:
I added this in my

app\Providers\AppServiceProvider.php

```<code>Product::created(function ($model) {
    $producthistory = new Producthistory();
    $producthistory >product_id = $model->id;
    $producthistory >action = ' Product Created';
    $producthistory >log = "Product created bla bla bla";
    $producthistory >action_by = Auth::id();
    $producthistory >save();
});
</code>```

Body:
I added this in my

app\Providers\AppServiceProvider.php

Product::created(function ($model) {
    $producthistory = new Producthistory();
    $producthistory >product_id = $model->id;
    $producthistory >action = ' Product Created';
    $producthistory >log = "Product created bla bla bla";
    $producthistory >action_by = Auth::id();
    $producthistory >save();
});


问:
How to style header in react-navigation
I am trying to style the header in react-navigation where the object is automatically generated by Expo.

I am trying to style the header background and the orientation of the title.

I tried every possible place, including navigationOptions but all failed.

In below code tab bar background color is correctly changed. But same method failed for header.

Any guidance appreciated.

```<code>import React from 'react';

import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';

import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';

const LinksStack = createStackNavigator({
    Links: LinksScreen,
});

LinksStack.navigationOptions = {
    tabBarLabel: "Links",
    tabBarIcon: ...
};

const SettingsStack = createStackNavigator({
    Settings: SettingsScreen,
});

SettingsStack.navigationOptions = {
    tabBarLabel: "Settings",
    tabBarIcon: ...,
};

export default createBottomTabNavigator(
    {
        LinksStack,
        SettingsStack,
    },
    {
        tabBarOptions: {
            style: {
                backgroundColor: '#123456',
            },
        }
    },
);

</code>```

答:
Finally I figured out what I was doing wrong.

It seems I was searching the answer in wrong place. The following change solved the problem:

```<code>class LinksScreen extends React.Component {
    static navigationOptions = {
        title: "Links Title",
        headerStyle: { backgroundColor: '#123456', },
        headerTitleStyle: { color: "#654321" },
    };
...
}
</code>```

Title: How to style header in react-navigation

Body:
I am trying to style the header in react-navigation where the object is automatically generated by Expo.

I am trying to style the header background and the orientation of the title.

I tried every possible place, including navigationOptions but all failed.

In below code tab bar background color is correctly changed. But same method failed for header.

Any guidance appreciated.

import React from 'react';

import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';

import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';

const LinksStack = createStackNavigator({
    Links: LinksScreen,
});

LinksStack.navigationOptions = {
    tabBarLabel: "Links",
    tabBarIcon: ...
};

const SettingsStack = createStackNavigator({
    Settings: SettingsScreen,
});

SettingsStack.navigationOptions = {
    tabBarLabel: "Settings",
    tabBarIcon: ...,
};

export default createBottomTabNavigator(
    {
        LinksStack,
        SettingsStack,
    },
    {
        tabBarOptions: {
            style: {
                backgroundColor: '#123456',
            },
        }
    },
);

Body:
Finally I figured out what I was doing wrong.

It seems I was searching the answer in wrong place. The following change solved the problem:

class LinksScreen extends React.Component {
    static navigationOptions = {
        title: "Links Title",
        headerStyle: { backgroundColor: '#123456', },
        headerTitleStyle: { color: "#654321" },
    };
...
}


问:
I can't seem to link html to css
```<code>    <!DOCTYPE html>
<html>
  <head>
    <link href="style.css" rel="designpage" type="text/css">
    <title> Viktoria Niemann </title>
  </head>
  <body>
    <h1>Dear Vik</h1>
    <ul>
      <li><a href= "index.html">Home</a></li>
      <li><a href="about.html">About</a></li>
      <li><a href="gallery.html">Gallery</a></li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
    <img src="https://upload.wikimedia.org/wikipedia/commons/3/33/-LOVE-love-36983825-1680-1050.jpg">

  </body>
</html>
</code>```

I am not sure why html is not linking to css. I think i have written a code correctly

答:
to achieve this you would change the rel to stylesheet instead of designpage.
The rel is required because it specifies the relationship between the document you are working on and the document

<link href="style.css" rel="stylesheet" type="text/css">```

Title: I can't seem to link html to css

Body:
    <!DOCTYPE html>

    <link href="style.css" rel="designpage" type="text/css">
    <title> Viktoria Niemann </title>

Dear Vik

Home

About

Gallery

Contact

I am not sure why html is not linking to css. I think i have written a code correctly


问:
App get crashed in Core data but unable to find where it crashed
I am creating an IOS app including CoreData with Objective c. I am getting some core data error but unable to find on which line I am getting that error.

The error is showing in Firebase

CoreData
  -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:]

```<code>Crashed: com.apple.main-thread
  EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000007fe226a10
 -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:]
</code>```

答: EXC_BAD_ACCESS KERN_INVALID_ADDRESS crash occurs when you try to access a deallocated object. Tracking with proper breakpoints might help.</p>

Body:
I am creating an IOS app including CoreData with Objective c. I am getting some core data error but unable to find on which line I am getting that error.

The error is showing in Firebase

CoreData
  -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:]

Crashed: com.apple.main-thread
  EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000007fe226a10
 -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:]