Angular如何响应动态和原始JSON对象?

huangapple go评论70阅读模式
英文:

How does Angular respond with a dynamic and raw JSON object?

问题

如果将一个JSON文件放在assets目录下,像http://localhost:4200/myapp.com/assets/hello.json这样调用将会直接检索到JSON文件,而不包含GUI。这意味着Angular应该知道如何返回一个原始的JSON对象。

现在,与其使用静态JSON文件,我想创建一个JSON对象内容,这样Angular将返回一个动态的JSON对象。例如,http://localhost:4200/echo?input=world将返回{"hello": "world"}

基于收到的评论更新的用例
这里的真正用例是,我有一个独立的第三方前端应用程序,我将它嵌入到我的Angular应用程序中,并在Angular组件中使用iFrame来显示它。然而,这个嵌入的应用程序需要一些数据来动态自定义用户的显示。我们可以通过调用API来实现这一点,但这需要不必要地调用后端,因为Angular应用程序已经获取了这些信息,而且调用后端会产生成本。

因此,我想知道是否有一种快捷方式让嵌入的应用程序调用父Angular。也许我的问题应该是“Web服务器如何根据查询字符串返回原始的JSON对象”。

英文:

If a JSON file is put under assets, calling something like http://localhost:4200/myapp.com/assets/hello.json will retrieve the JSON file as is, without the GUI. That means Angular should know how to return a raw JSON object.

Now, instead of a static JSON file, I would like to create a JSON object content so that Angular will return a dynamic JSON object. For example, http://localhost:4200/echo?input=world will return {"hello": "world"}

Updated use case based on comment received:
The real use case here is I have a 3rd party independent frontend app, which I embed it with my Angular app and display it in an Angular component using iFrame. However, this embedded app requires some data for customizing the display for the user dynamically. We can do this by calling API but this requires a unnecessary call to the backend as the Angular app has already got that information, plus there is a cost incurred to call the backend.

Hence I would like to see if there is a shortcut to let the embedded app calling the parent Angular. Maybe my question should be "How can a webserver return a raw JSON object based on the query string"

答案1

得分: 1

以下是翻译好的部分:

通过queryParamMapjson pipe的组合来显示动态JSON。

这是一个使用json pipe的StackBlitz实现

以下是使用URL参数获取JSON路径和要添加到JSON中的输入的代码示例。

示例URL:http://localhost:4200/echo?input=world&jsonPath=hello.json

import { Component, inject, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { firstValueFrom, Subscription } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'echo',
    template: '<div>{{ jsonData | json }}</div>',
})
export class Echo implements OnInit, OnDestroy {
    private http = inject(HttpClient);
    private queryParamSubscription: Subscription;
    private readonly activatedRoute = inject(ActivatedRoute);

    jsonData: any;

    async ngOnInit(): Promise<void> {
        this.queryParamSubscription =
            this.activatedRoute.queryParamMap.subscribe(async (map): Promise<void> => {
                const input = map.get('input') as string;
                // 假设输入包含'world'

                const jsonPath = map.get('jsonPath') as string;
                // 假设jsonPath包含'hello.json'

                const jsonFileData = await this.getJsonData(jsonPath);

                // 假设hello.json包含{ "hello": "" }
                jsonFileData.hello = input;
                // 现在包含{ "hello": "world" }

                this.jsonData = jsonFileData;
            });
    }

    getJsonData(jsonPath: string): Promise<any> {
        return firstValueFrom(this.http.get<any>(`assets/${jsonPath}`));
    }

    ngOnDestroy(): void {
        if (this.queryParamSubscription) {
            this.queryParamSubscription.unsubscribe();
        }
    }
}
英文:

With a combination of queryParamMap and json pipe to display dynamic json

Here is a stackblitz implementation of json pipe

Here is the code using the url params to get the json path and the input you want to add in the json.

Example url: http://localhost:4200/echo?input=world&jsonPath=hello.json

import { Component, inject, OnDestroy, OnInit } from &#39;@angular/core&#39;;
import { ActivatedRoute } from &#39;@angular/router&#39;;
import { firstValueFrom, Subscription } from &#39;rxjs&#39;;
import { HttpClient } from &#39;@angular/common/http&#39;;
@Component({
selector: &#39;echo&#39;,
template: `&lt;div&gt;{{ jsonData | json }}&lt;/div&gt;`,
})
export class Echo implements OnInit, OnDestroy {
private http = inject(HttpClient);
private queryParamSubscription: Subscription;
private readonly activatedRoute = inject(ActivatedRoute);
jsonData: any;
async ngOnInit(): Promise&lt;void&gt; {
this.queryParamSubscription =
this.activatedRoute.queryParamMap.subscribe(async (map): Promise&lt;void&gt; =&gt; {
const input = map.get(&#39;input&#39;) as string;
// Pretend input contains &#39;world&#39;
const jsonPath = map.get(&#39;jsonPath&#39;) as string;
// Pretend jsonPath contains &#39;hello.json&#39;
const jsonFileData = await this.getJsonData(jsonPath);
// Pretend hello.json contains { &quot;hello&quot;: &quot;&quot; }
jsonFileData.hello = input;
// Now contains { &quot;hello&quot;: &quot;world&quot; }
this.jsonData = jsonFileData;
});
}
getJsonData(jsonPath: string): Promise&lt;any&gt; {
return firstValueFrom(this.http.get&lt;any&gt;(`assets/${jsonPath}`));
}
ngOnDestroy(): void {
if (this.queryParamSubscription) {
this.queryParamSubscription.unsubscribe();
}
}
}

huangapple
  • 本文由 发表于 2023年5月25日 20:25:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定