Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.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
如何为angular 6中的所有组件使用公共类url?_Angular - Fatal编程技术网

如何为angular 6中的所有组件使用公共类url?

如何为angular 6中的所有组件使用公共类url?,angular,Angular,我有一个公共类,该公共类在所有组件中导入,该公共类url在所有组件中使用,但该公共url不起作用,因此如何在angular中为所有组件创建公共url(因为将来我必须仅在公共类中为commonUrl进行更改) category.component.html <button mat-button><img src="commonUrl/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/><

我有一个公共类,该公共类在所有组件中导入,该公共类url在所有组件中使用,但该公共url不起作用,因此如何在angular中为所有组件创建公共url(因为将来我必须仅在公共类中为commonUrl进行更改)

category.component.html

<button mat-button><img src="commonUrl/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/></button>
 <td mat-cell *matCellDef="let element"> 
   <img src="commonUrl/{{element.userimage}}" style="height: 40px;width: 40px;"/>
 </td>

follow.component.html

<button mat-button><img src="commonUrl/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/></button>
 <td mat-cell *matCellDef="let element"> 
   <img src="commonUrl/{{element.userimage}}" style="height: 40px;width: 40px;"/>
 </td>

最好创建一个静态变量来访问公共url

export class CommonClass {
  public static commonUrl : string = 'http://localhost:3000'
}
在category.component.ts中访问该属性

categoryimage = CommonClass.commonUrl 

<button mat-button><img src="commonUrl/{{categoryimage}}" style="height: 100px;width: 100px;"/></button>
categoryimage=CommonClass.commonUrl

app.module.ts
文件中为url添加提供程序。您的代码应该如下所示

@NgModule({
   declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        ...........
    ],
    providers: [
        ........
        //use this line   
        { provide: 'API_URL', useValue: 'http://localhost:3000' },
    ]
})
在你的组件中,你必须注入它

export class YourComponent {
    apiUrl: string;

    constructor(@Inject('API_URL') apiUrl: string) {
        this.apiUrl = apiUrl;
    }
}

现在,您可以在组件中的任何位置使用该url,首先需要在组件中导入类,然后在视图中创建该类的实例

这里有一个例子

.ts中

import {CommonClass} from ../yourfolder/commomurl

commonClassObj: CommonClass = new CommonClass();
.html

<button mat-button><img src="{{commonClassObj.commonUrl}}/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/></button>

如果不起作用,另一种方法是:使用输出来发出值

 @Output() commonUrl : EventEmitter<Boolean> = new EventEmitter<Boolean>();
并在要使用此通用URL的组件中使用@Input()


希望它有帮助

最好的方法是使用文件夹
environnements
中的文件

在文件
environnement.dev.ts
中:

export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000',
};
使用环境变量:

import { environment } from '../../environments/environment';
在您的组件中:

apiUrl = environment.apiUrl;