PaulTMatik
@PaulTMatik

Почему Angular 4 говорит что не знает атрибут компонента, не смотря на то, что он указан?

persons.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { IPerson } from "../../share/iperson";

@Component({
    selector: 'app-persons',
    templateUrl: './persons.component.html',
    styleUrls: ['./persons.component.css']
})
export class PersonsComponent implements OnInit {
    @Input() public persons: Observable<IPerson[]>;
    constructor() { }
    ngOnInit() {
    }
}


persons.component.html
<ul>
  <li *ngFor="let person of persons | async">
    <p><strong>{{person.GetShortName()}}</strong></p>
    <p><em>{{person.GetAdditionalInfo()}}</em></p>
  </li>
</ul>

Данный компонент используется в двух модулях: employees.module.ts и students.module.ts
students.component.html
<app-persons [persons]="students">
  <p *ngIf="(students | async)?.length === 0">Список студентов пуст</p>
</app-persons>

students.component.ts
import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import { StudentsService } from "./students.service";
import { ActivatedRoute, Router, ParamMap } from "@angular/router";
import { Observable } from "rxjs/Observable";

import { Student } from "../share/student";

@Component({
    selector: 'app-students',
    templateUrl: './students.component.html',
    styleUrls: ['./students.component.css']
})
export class StudentsComponent implements OnInit {
    students: Observable<Student[]>;
    selectedStudentUid: string;
    constructor(
        private _service: StudentsService,
        private _route: ActivatedRoute,
        private _router: Router
    ) { }

    ngOnInit() {
        this.students = this._route.paramMap
            .switchMap((params: ParamMap) => {
                this.selectedStudentUid = params.get('id');
                return this._service.GetAll();
            });
    }
}

Сайт запускается, но при попытке открыть какую либо из страниц, указанных выше, вываливается ошибка:
ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'persons' since it isn't a known property of 'app-persons'.
1. If 'app-persons' is an Angular component and it has 'persons' input, then verify that it is part of this module.
2. If 'app-persons' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("<app-persons [ERROR ->][persons]="students">
  <p *ngIf="(students | async)?.length === 0">Список студентов пуст</p>
</app"): ng:///StudentsModule/StudentsComponent.html@0:13
'app-persons' is not a known element:
1. If 'app-persons' is an Angular component, then verify that it is part of this module.
2. If 'app-persons' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<app-persons [persons]="students">
  <p *ngIf="(students | async)?.length === 0">Список студентов пу"): ng:///StudentsModule/StudentsComponent.html@0:0
Error: Template parse errors:
Can't bind to 'persons' since it isn't a known property of 'app-persons'.
1. If 'app-persons' is an Angular component and it has 'persons' input, then verify that it is part of this module.
2. If 'app-persons' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("<app-persons [ERROR ->][persons]="students">
  <p *ngIf="(students | async)?.length === 0">Список студентов пуст</p>
</app"): ng:///StudentsModule/StudentsComponent.html@0:13
'app-persons' is not a known element:
1. If 'app-persons' is an Angular component, then verify that it is part of this module.
2. If 'app-persons' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<app-persons [persons]="students">
  <p *ngIf="(students | async)?.length === 0">Список студентов пу"): ng:///StudentsModule/StudentsComponent.html@0:0...

Если компонент persons указать в модуле: employees.module или students.module, то всё работает, но я не могу указать один компонент в двух параллельных модулях, только в родительском, а там вот такая петрушка! Что я сделал не так?
  • Вопрос задан
  • 5879 просмотров
Решения вопроса 2
PaulTMatik
@PaulTMatik Автор вопроса
Нашёл ответ, проблема не в атрибуте, а в том, что Angular не компилировался с данным компонентом вообще, оказывается компонент может быть размещён только в одном модуле в принципе и если нужно использовать один компонент в разных, то его нужно вынести в свой собственный модуль, а затем подключить в тех, где он будет использоваться.
persons.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { PersonsComponent } from "./persons.component";

@NgModule({
    imports: [
        CommonModule
    ],
    declarations: [
        PersonsComponent
    ],
    exports: [
        CommonModule, PersonsComponent
    ]
})
export class PersonsModule { }

Как-то я невнимательно читал документацию
Ответ написан
@furrya_black
Может стоит передавать данные в компонент через Subject?

То есть пусть будет message.service умеющий только sendMessage, getMessage, clearMessage глобальный для всех модулей.

А конкретно для вашего модуля и-компонента пусть будет persons.service, создающий новые экземпляры классов message.service. В одном компоненте мы делаем sendMessage в другом get Message.subscribe

https://bitbucket.org/furrya_black/cake-shop
Для примера, как я это делал.

В папке app/services сервис message.service
Посмотрите как он используется. Там же есть loader.service и в папке app/containers. Для каждого узконаправленного message сервиса создается новый инстанс message сервиса.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы