![](/img/trans.png)
[英]Array in parent component cannot be assigned from a child component in angular2
[英]cannot display array sent from one component to other in angular2
服務 -
import {Injectable} from '@angular/core';
import {UserData} from '../user-data/user-data.component';
@Injectable()
export class UserDataService {
constructor(){}
userdata:UserData[];
getData(){
console.log('service',this.userdata);
return this.userdata;
}
setData(user:any){
this.userdata=user;
console.log(this.userdata);
}
}
用戶數據類-
export class UserData {
firstname: string;
middlename: string;
lastname: string;
email: string;
contact: number;
}
組件1-
import { Component,OnInit,OnDestroy } from '@angular/core';
import { UserData } from '../../user-data/user-data.component';
import { ViewEditUser } from '../../view-edit-user/view-edit-user.component';
import {UserDataService} from '../../user-data-service/user-data-service.service';
@Component({
selector: 'form-page',
templateUrl: `app/add-user-sidebar/user-form/form.component.html`,
providers:[UserDataService]
})
export class Form implements OnInit,OnDestroy {
userdetail:UserData;
constructor(private service:UserDataService){
}
addUser(first:string,middle:string,last:string,emailid:string,contactno:number){
this.userdetail=({firstname:first,middlename:middle,lastname:last,email:emailid,contact:contactno})
console.log(this.userdetail);
this.service.setData(this.userdetail);
}
ngOnInit(){
}
ngOnDestroy(){
}
}
Component2--
import { Component,Input, OnInit } from '@angular/core';
import { Form } from '../add-user-sidebar/user-form/form.component';
import {UserData} from '../user-data/user-data.component';
import { WelcomePage } from '../welcome-page/welcome-page.component';
import {UserDataService} from '../user-data-service/user-data-service.service';
@Component({
selector:'view-edit',
templateUrl: 'app/view-edit-user/view-edit-user.component.html',
providers: [UserDataService]
})
export class ViewEditUser implements OnInit {
arraydata:any;
constructor(private service:UserDataService){}
// arraydata:any;
printarray(){
console.log(this.arraydata);
}
ngOnInit()
{
this.arraydata=this.service.getData();
console.log("hhghdfghdf",this.arraydata);
}
}
我是angular2的新手,我的模塊中有兩個組件,一個組件是用戶輸入數據的一種形式,然后將數據發送到服務,當我進行console.log記錄時,便可以看到服務中的數據。 但是當我嘗試從第二個組件訪問該數組時,我無法訪問該怎么辦?
如果在每個組件上提供服務,則不能將其用於通信,因為每個組件將獲得不同的服務實例。
如果一個組件是另一組件的父級(祖先),則僅在父級組件上提供它。 否則,在作為兩者的父級(anjestor)的組件上提供它,或者僅在@NgModule()
提供它以使服務成為全局。
您還需要注意,一個組件可能會在另一個組件設置值之前讀取,具體取決於您在何處設置該值以及創建組件的順序。 使用BehaviorSubject
通常可以避免這種陷阱,因為通過這種方式,首先創建哪個組件或一個組件嘗試讀取而另一個組件尚未設置值並不重要。
有關在Angular實例之間共享的信息,另請參閱如何在兩個模塊之間共享服務-angular2中的@NgModule?
您需要使用可觀察對象在組件之間傳遞數據。
在您的服務中,創建一個Subject類型變量,然后在您的第一個組件中執行.next,以將數據傳遞給該服務;在您的第二個組件中,訂閱服務veriable,它將為您獲取數據。
由於JavaScript的異步行為(將由可觀察對象處理),因此您無法獲取數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.