[英]How to use one component data in another component in angular 6?
I have a component.ts file which is making a http call & retrieving json data as response.我有一个 component.ts 文件,它正在进行 http 调用并检索 json 数据作为响应。 I need to use this response in another component.ts file.我需要在另一个 component.ts 文件中使用这个响应。 Can anyone tell me how to process this?谁能告诉我如何处理这个? first component.ts:第一个组件.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));
});
}
I need to use the json content which is in the response in my second component file.我需要使用我的第二个组件文件的响应中的 json 内容。 Can anybody tell me how to proceed this in angular6?谁能告诉我如何在 angular6 中进行此操作?
****Create separate service for making calls and in that service create a method as such ****为拨打电话创建单独的服务,并在该服务中创建一个方法
public getData(): Observable<> {
return this.http.get('/name',{responseType:"json"}).subscribe(
response => {
console.log("data :"+response);
console.log("data stringify:"+JSON.stringify(response));
});
}
****And in your component declare service in constructor //don't forget to import it ****在你的组件中声明服务在构造函数中 //不要忘记导入它
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)
);
}
Finally,you can use jsonData to work with your data.最后,您可以使用 jsonData 处理您的数据。
Parent to Child: Sharing Data via Input父母对孩子:通过输入共享数据
parent.component.ts父组件.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 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() { }
}
Sharing Data via Output() and EventEmitter通过 Output() 和 EventEmitter 共享数据
parent.component.ts父组件.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 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)
}
}
please visit https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/ for other methods.请访问https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/了解其他方法。
Use Input & Output Decorators使用输入和输出装饰器
Basic concept ---> DEMO基本概念---> DEMO
app.component.html: 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: app.component.ts:
datatocomp2: any;
catch1Data(data) {
console.log(data)
this.datatocomp2 = data;
}
component1.ts:组件1.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:组件2.ts:
@Input() elm: any;
constructor() { }
ngOnInit() {
console.log(this.elm);
}
Solution 1 using a common injectible service解决方案 1 使用通用的可注入服务
Shared.service.ts共享服务.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));
});
}
}
Solution 2 using a parent child component解决方案 2 使用父子组件
Second.component.ts第二个.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父组件.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{ }
You can create store service for your 'global' data:您可以为您的“全球”数据创建存储服务:
store.service.ts 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);
}
}
And then in yours component (lets call it X) you save data to store:然后在你的组件中(让我们称之为 X)你保存数据来存储:
x.component.ts 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));
});
}
And then in yours other component (lets call it Y) you get your data:然后在你的其他组件中(我们称之为 Y)你得到你的数据:
y.component.ts 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');
});
}
This is just simple example, if you know the structure of your response got by http call it would be good idea to make model of it.这只是一个简单的示例,如果您知道通过 http 调用获得的响应结构,那么制作它的模型是个好主意。 Using the store any component can get or set store data.使用 store 任何组件都可以获取或设置 store 数据。
If you need something more complex look for: @ngrx/store如果您需要更复杂的东西,请查找: @ngrx/store
Cases when you would not need store service:不需要门店服务的情况:
If you do that http call in parent component then you can use child inputs to pass the data.如果您在父组件中执行该 http 调用,那么您可以使用子输入来传递数据。
If you make that call in child component then use @Output and EventEmitter, to pass up the data (just one level, you can not do this to pass to grandparent)如果您在子组件中进行该调用,则使用@Output 和 EventEmitter 来传递数据(只是一个级别,您不能这样做以传递给祖父母)
Regards.问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.