我有一个component.ts文件,该文件正在进行http调用并检索json数据作为响应。我需要在另一个component.ts文件中使用此响应。谁能告诉我该如何处理? 第一个component.ts:
@Component({
selector: 'app-cat',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
})
export class firstComponent extends Lifecycle {
this.http.get('/name',{responseType:"json"}).subscribe(
response => {
console.log("data :"+response);
console.log("data stringify:"+JSON.stringify(response));
});
}
我需要使用第二个组件文件中响应中的json内容。有人可以告诉我如何在angular6中进行此操作吗?
答案 0 :(得分:0)
****创建用于拨打电话的单独服务,并在该服务中创建一个方法
public getData(): Observable<> {
return this.http.get('/name',{responseType:"json"}).subscribe(
response => {
console.log("data :"+response);
console.log("data stringify:"+JSON.stringify(response));
});
}
****并且在您的组件中声明构造函数中的服务//不要忘记导入它
public jsonData:any;
constructor(private Service: Service ) {
}
getData() {
this.Service.getData().subscribe(data => {
console.log("Data is ",data);
this.jsonData = data;
},
error => console.log(error)
);
}
最后,您可以使用jsonData处理数据。
答案 1 :(得分:0)
父级:通过输入共享数据
parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child [childMessage]="parentMessage"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
parentMessage = "message from parent"
constructor() { }
}
child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Say {{ message }}
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() childMessage: string;
constructor() { }
}
通过Output()和EventEmitter共享数据
parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Message: {{message}}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hola Mundo!"
@Output() messageEvent = new EventEmitter<string>();
constructor() { }
sendMessage() {
this.messageEvent.emit(this.message)
}
}
请访问https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/以了解其他方法。
答案 2 :(得分:0)
使用输入和输出装饰器
基本概念---> DEMO
app.component.html:
<app-component1 (elm)="catch1Data($event)">
</app-component1>
<app-component2 [elm]="datatocomp2" *ngIf="datatocomp2"></app-component2>
parent component : {{datatocomp2 | json}}
app.component.ts:
datatocomp2: any;
catch1Data(data) {
console.log(data)
this.datatocomp2 = data;
}
component1.ts:
@Output () elm : EventEmitter<any> = new EventEmitter<any>();
objectData: any;
constructor() { }
ngOnInit() {
let objectData = {
comp: 'component 1',
data: 'anything'
}
this.objectData = objectData;
this.elm.emit(objectData)
}
component2.ts:
@Input() elm: any;
constructor() { }
ngOnInit() {
console.log(this.elm);
}
答案 3 :(得分:0)
使用常见的可注射服务的解决方案1
Shared.service.ts
@Injectible()
class SharedService {
function getData():any{
return this.http.get('/name',{responseType:"json"}).subscribe(
response => {
console.log("data :"+response);
console.log("data stringify:"+JSON.stringify(response));
});
}
}
使用父子组件的解决方案2
Second.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-first-component',
template: `<p>{{data}}</p>`
})
export class SecondComponent{
data:any={};
ngOnInit(){this.getData();}
function getData():any{
this.http.get('/name',{responseType:"json"}).subscribe(
response => {
console.log("data :"+response);
console.log("data stringify:"+JSON.stringify(response));
this.data=data
});
}
}
parent.component.ts
import { Component } from '@angular/core';
import { SecondComponent } from './second.component';
@Component({
selector: 'app-first-component',
template: `
<h3>Get data (via local variable)</h3>
<button (click)="second.getData()">GetData</button>
<app-first-component #second></app-first-component>
`
})
export class FirstComponent{ }
答案 4 :(得分:0)
您可以为“全局”数据创建商店服务:
store.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class StoreService {
protected store: Map<string, any> = new Map();
constructor() { }
public get(key: string): any {
return this.store.get(key);
}
public set(key: string, value: any) {
this.store.set(key, value);
}
}
然后在您的组件(将其称为X)中保存要存储的数据:
x.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClinet } from '@angular/common/http';
import { StoreService } from './store-service.service.ts';
@Component({
selector: 'app-x',
templateUrl: './x.component.html',
styleUrls: ['./x.component.css']
})
export class XComponent implements OnInit {
constructor(
private store: StoreService,
private http: HttpClient,
) { }
ngOnInit() {
}
getResource() {
this.http.get('/name',{responseType:"json"}).subscribe(
response => {
this.store.set('response', response);
console.log("data :"+response);
console.log("data stringify:"+JSON.stringify(response));
});
}
然后在您的其他组件(简称为Y)中,获取数据:
y.component.ts
import { Component, OnInit } from '@angular/core';
import { StoreService } from './store-service.service.ts';
@Component({
selector: 'app-y',
templateUrl: './y.component.html',
styleUrls: ['./y.component.css']
})
export class YComponent implements OnInit {
constructor(
private store: StoreService
) { }
ngOnInit() {
}
getSavedResponse() {
// ask store for the resource
return this.store.get('response');
});
}
这只是简单的示例,如果您知道通过http调用获得的响应的结构,则最好对其进行建模。 使用商店,任何组件都可以获取或设置商店数据。
如果您需要更复杂的内容,请寻找:@ngrx/store
不需要商店服务时的情况:
如果您在父组件中进行了http调用,则可以使用子输入来传递数据。
如果在子组件中进行该调用,然后使用@Output和EventEmitter传递数据(仅一个级别,则不能传递给祖父母)
致谢。