我尝试在另一个组件中使用组件的方法但是我得到的错误就像没有xxComponent的提供程序一样。 我该怎么办?
import { FoldersService } from '../../_services/folders.service';
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-folder-create',
templateUrl: './folder-create.component.html',
})
export class FolderCreateComponent implements OnInit {
constructor(
private http: Http,
private folderService: FoldersService,
) { }
ngOnInit() { }
saveFolder() {
}
}
-- Class FolderEditComponent
import { FolderCreateComponent } from '../folder-create/folder-create.component';
@Component({
selector: 'app-folder-edit',
templateUrl: './folder-edit.component.html',
styleUrls: ['./folder-edit.component.css'],
})
export class FolderEditComponent implements OnInit {
constructor(
private http: Http,
private folderService: FoldersService,
private folderCreate: FolderCreateComponent
) { }
ngOnInit() { }
// How can I do here for calling method saveFolder() of the component FolderCreateComponent
// I try this :
folderCreate.saveFolder(); // But I got error : ERROR Error: Uncaught (in promise): Error: No provider for FolderCreateComponent!
}
如何在组件FolderEditComponent中调用组件FolderCreateComponent的方法saveFolder()?
答案 0 :(得分:2)
案例1 - 当您想要访问子组件的方法时,则在父组件中 -
(function($) {
var $test,
isMobile = false;
function checkTest() {
if ($test.length) {
isMobile = $test.css('z-index')=='2';
}
}
$(function() {
$test = $('#test');
checkTest();
});
$(window).on('resize',function() {
checkTest();
});
// in the rest of your code you can now simply check if isMobile is true
})(jQuery);
案例2 - 当你想要从孩子那里访问父方法时 -
构造函数(@Inject(forwardRef(()=> ParentComponent))private _parent:ParentComponent){}
只需使用@ViewChild(ChildComponent) childComponent: ChildComponent;
childComponent.methodName();
答案 1 :(得分:1)
您需要将服务添加到组件中使用的提供程序:
@Component({
selector: 'app-folder-create',
templateUrl: './folder-create.component.html',
providers: [FoldersService]
})
此外,您还需要使用import {FooComponent} from '/path/to/foo.component';
导入组件,以便在另一个组件中使用组件。
编辑:
import {FolderCreateComponent} from 'path/to/component';
export class FolderEditComponent implements OnInit {
constructor(private folderCreate: FolderCreateComponent) {
}
foo() { this.folderCreate.saveFolder(); }
}
答案 2 :(得分:1)
为FolderCreateComponent
import { FoldersService } from '../../_services/folders.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Http, Response } from '@angular/http';
@Component({
selector: 'app-folder-create',
templateUrl: './folder-create.component.html',
providers: [FoldersService]
})
export class FolderCreateComponent implements OnInit {
constructor(
private http: Http,
private folderService: FoldersService,
) { }
ngOnInit() { }
saveFolder() {
}
}