Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular5:将变量从一个组件传递到另一个Typescript文件_Angular_Typescript_Input - Fatal编程技术网

Angular5:将变量从一个组件传递到另一个Typescript文件

Angular5:将变量从一个组件传递到另一个Typescript文件,angular,typescript,input,Angular,Typescript,Input,我试图将存储在一个组件中的值传递给另一个组件,以便新组件可以使用原始组件中的选定值。现在我有一个文件如下: 符号选择器.component.ts 从'@angular/core'导入{Component,Input,OnInit}; @组成部分({ 选择器:“应用程序符号选择器”, templateUrl:'./symbol picker.component.html', 样式URL:['./symbol picker.component.scss'] }) 导出类SymbolPickerCo

我试图将存储在一个组件中的值传递给另一个组件,以便新组件可以使用原始组件中的选定值。现在我有一个文件如下:

符号选择器.component.ts

从'@angular/core'导入{Component,Input,OnInit};
@组成部分({
选择器:“应用程序符号选择器”,
templateUrl:'./symbol picker.component.html',
样式URL:['./symbol picker.component.scss']
})
导出类SymbolPickerComponent实现OnInit{
selectionChoice:字符串;
equalsTxt='=';
impliesTxt='=>';
构造函数(){}
恩戈尼尼特(){
}

}
在组件之间共享数据的方法有很多种。对于您的特定场景,您的最佳选择是服务。构建服务以保留您想要共享的价值

然后将服务注入任何需要设置值或读取值的组件中

我举了一个例子:

在我的例子中,我共享当前选择的电影。下面是我的一些代码片段。(有关完整的代码示例,请参见上面的URL。)

电影服务:

@Injectable()
export class MovieService {

    currentMovie: IMovie | null;
    // Other code here.
}
电影列表组件

在此组件中,用户选择一部电影:

export class MovieListComponent {
    constructor(private movieService: MovieService) { }

    onSelected(movie: IMovie): void {
        this.movieService.currentMovie = movie;
    }
    // Other code here
}
电影细节组件

在这个组件中,当用户在电影列表组件中选择不同的电影时,绑定会自动更改

UI绑定到下面组件中定义的
电影
属性

export class MovieDetailComponent {

    get movie(): IMovie | null {
        return this.movieService.currentMovie;
    }

    constructor(private movieService: MovieService) {}
}

Angular的更改检测跟踪
currentMovie
在服务中的更改并重新绑定值,调用上面显示的getter并获取
currentMovie
的当前值组件之间共享数据的方法有很多。对于您的特定场景,您的最佳选择是服务。构建服务以保留您想要共享的价值

然后将服务注入任何需要设置值或读取值的组件中

我举了一个例子:

在我的例子中,我共享当前选择的电影。下面是我的一些代码片段。(有关完整的代码示例,请参见上面的URL。)

电影服务:

@Injectable()
export class MovieService {

    currentMovie: IMovie | null;
    // Other code here.
}
电影列表组件

在此组件中,用户选择一部电影:

export class MovieListComponent {
    constructor(private movieService: MovieService) { }

    onSelected(movie: IMovie): void {
        this.movieService.currentMovie = movie;
    }
    // Other code here
}
电影细节组件

在这个组件中,当用户在电影列表组件中选择不同的电影时,绑定会自动更改

UI绑定到下面组件中定义的
电影
属性

export class MovieDetailComponent {

    get movie(): IMovie | null {
        return this.movieService.currentMovie;
    }

    constructor(private movieService: MovieService) {}
}

Angular的更改检测跟踪
currentMovie
在服务中的更改并重新绑定值,调用上面显示的getter,获取当前电影的当前值使用@InputUse for the@InputHanks for the response我不确定解决问题的最佳方法是什么,但服务是有意义的回答我不确定解决问题的最佳方法是什么,但服务是有意义的