get value from another component angular 4

后端 未结 3 1046
孤城傲影
孤城傲影 2020-12-25 08:18

I have two separate components; a header component containing a select search box, stats component that shows the results depending on the value of the select box, I was won

3条回答
  •  自闭症患者
    2020-12-25 09:05

    Use Shared Services:

    Service:

    @Injectable()
    export class MyService {
        myMethod$: Observable;
        private myMethodSubject = new Subject();
    
        constructor() {
            this.myMethod$ = this.myMethodSubject.asObservable();
        }
    
        myMethod(data) {
            console.log(data); // I have data! Let's return it so subscribers can use it!
            // we can do stuff with data if we want
            this.myMethodSubject.next(data);
        }
    }
    

    Component1 (sender):

    export class SomeComponent {
        public data: Array = MyData;
    
        public constructor(private myService: MyService) {
            this.myService.myMethod(this.data);
        }
    }
    

    Component2 (receiver):

    export class SomeComponent2 {
        public data = {};
    
        public constructor(private myService: MyService) {
            this.myService.myMethod$.subscribe((data) => {
                    this.data = data; // And he have data here too!
                }
            );
        }
    }
    

    Check documentation!

提交回复
热议问题