Tôi có một đối tượng mà tôi muốn chia sẻ giữa các thành phần của mình với ứng dụng Angular2.Angular2 - Chia sẻ dữ liệu giữa các thành phần sử dụng dịch vụ
Đây là nguồn gốc của thành phần đầu tiên:
/* app.component.ts */
// ...imports
import {ConfigService} from './config.service';
@Component({
selector: 'my-app',
templateUrl: 'app/templates/app.html',
directives: [Grid],
providers: [ConfigService]
})
export class AppComponent {
public size: number;
public square: number;
constructor(_configService: ConfigService) {
this.size = 16;
this.square = Math.sqrt(this.size);
// Here I call the service to put my data
_configService.setOption('size', this.size);
_configService.setOption('square', this.square);
}
}
và thành phần thứ hai:
/* grid.component.ts */
// ...imports
import {ConfigService} from './config.service';
@Component({
selector: 'grid',
templateUrl: 'app/templates/grid.html',
providers: [ConfigService]
})
export class Grid {
public config;
public header = [];
constructor(_configService: ConfigService) {
// issue is here, the _configService.getConfig() get an empty object
// but I had filled it just before
this.config = _configService.getConfig();
}
}
và cuối cùng là dịch vụ nhỏ của tôi, các ConfigService:
/* config.service.ts */
import {Injectable} from 'angular2/core';
@Injectable()
export class ConfigService {
private config = {};
setOption(option, value) {
this.config[option] = value;
}
getConfig() {
return this.config;
}
}
Dữ liệu của tôi không được chia sẻ, trong grid.component.ts, dòng _configService.getConfig()
trả về một đối tượng trống, bu Nó được điền ngay trước trong app.component.ts.
Tôi đã đọc tài liệu và hướng dẫn, không có gì hiệu quả.
Tôi đang thiếu gì?
Cảm ơn
SOLVED
Vấn đề của tôi là tôi đã được tiêm ConfigService tôi hai lần. Trong bootstrap của ứng dụng và trong tập tin mà tôi đang sử dụng nó.
Tôi đã xóa cài đặt providers
và hoạt động của thiết bị!
Lưu ý phụ, di chuyển cuộc gọi dịch vụ ra khỏi hàm tạo. – Stanislasdrg
http://www.angulartutorial.net/2017/09/angular-share-data-between-components.html – Prashobh